Question

I wanted to experiment with being able to have a converter whose arguments can be bound with the current data context. Can anyone tell me why when reaching the Convert() function, the Source property is always null?

namespace WpfApplication32
{
    public class ConverterTest : DependencyObject, IValueConverter
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(DependencyObject), typeof(ConverterTest));

        public DependencyObject Source
        {
            get { return (DependencyObject)this.GetValue(SourceProperty); }
            set { this.SetValue(SourceProperty, value); }
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value;
        }
    }

    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            Value = 7;

            InitializeComponent();
            DataContext = this;
        }

        public float Value
        {
            get;
            set;
        }
    }
}




<Window x:Class="WpfApplication32.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication32">

    <Slider>
        <Slider.Value>
            <Binding Path="Value">
                <Binding.Converter>
                    <local:ConverterTest Source="{Binding}"/>
                </Binding.Converter>
            </Binding>
        </Slider.Value>
    </Slider>

</Window>
Was it helpful?

Solution

One possible solution is to make your Converter inherit from Freezable instead (Hillberg Freezable trick). Then you can even define your Converter in your Resources and reference it in your binding as an attribute instead of an extra child element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top