Get the Source value in ConvertBack() method for IValueConverter implementation in WPF binding

前端 未结 5 1552
醉梦人生
醉梦人生 2021-01-02 12:05

I am binding a dependency property to textboxex in WPF. The property is a string that has some values separated by \'/\' (example: \"1/2/3/4\" ). I need to bind individual v

5条回答
  •  无人及你
    2021-01-02 12:32

    Update

    You have probably solved your issue already with the help of Vlad, I just thought I should add another way of actually getting the source value in the converter.

    First you could make your converter derive from DependencyObject so you can add a Dependency Property to it which we shall bind to

    public class MyConverter : DependencyObject, IValueConverter
    {
        public static DependencyProperty SourceValueProperty =
            DependencyProperty.Register("SourceValue",
                                        typeof(string),
                                        typeof(MyConverter));
        public string SourceValue
        {
            get { return (string)GetValue(SourceValueProperty); }
            set { SetValue(SourceValueProperty, value); }
        }
    
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //...
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            object targetValue = value;
            object sourceValue = SourceValue;
            //...
        }
    }
    

    Unfortunately, a Converter doesn't have a DataContext so the Binding won't work out of the box but you can use Josh Smith's excellent DataContextSpy: Artificial Inheritance Contexts in WPF

    
        
            
        
        
            
                
                    
                
            
        
    
    

    End of Update

    Dr.WPF has an elegant solution to this, see the following thread
    The way to access binding source in ConvertBack()?

    Edit

    Using the solution by Dr.WPF, you could supply both the string index and the source TextBox to the converter with this (perhaps a little verbose) sample code

    
        
            
                
                    
                        1
                        
                    
                
            
        
    
    

    And then you could later access both the index and the TextBox in the ConvertBack method

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        object[] parameters = parameter as object[];
        short index = (short)parameters[0];
        object source = (parameters[1] as TextBox).DataContext;
        //...
    }
    

提交回复
热议问题