2

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>
hammer
  • 145
  • 1
  • 10

1 Answers1

3

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.

Blachshma
  • 17,097
  • 4
  • 58
  • 72
Alan
  • 7,875
  • 1
  • 28
  • 48
  • Thank you, that seemed to work, but I dont know why. Why is it that the original code didnt work? I feel Im missing knowledge which is required before the workaround you linked to makes sense. – hammer Dec 08 '12 at 15:38
  • 1
    Basically, for some reason Freezable inherits the DataContext while most resources and things that are not part of the visual tree do not. They are special. Here.. this explains more http://drwpf.com/blog/2008/05/22/leveraging-freezables-to-provide-an-inheritance-context-for-bindings/ – Alan Dec 08 '12 at 17:43
  • This totally got me, it was pain – luis_laurent Dec 14 '19 at 02:40