Question

I'm trying to define a converter for some of the controls on my Window. The way I (and most people) usually do it is define the converter in its own class, instantiate an instance of that class in Window.Resources and then use it. The problem in this particular case is that the converter needs to access the window's DataContext,so I decided to implement it in the window's code behind:

public partial class MyWindow : Window, IValueConverter
{
    public MyWindow()
    {
        InitializeComponent();

        // Other operations  
    }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // Access the DataContext and return a value
        return new object();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
       throw new NotImplementedException();
    }
}

The problem is I can't figure out how to use it in XAML now. Obviously I don't want to instantiate a new instance of this class since I would lose the data context. I tried

"{Binding ElementName=someElement, Path=SomeProperty, Converter={Binding ElementName=myWindow}"

Where myWindow is the name of this window. I get a runtime error saying:

"A 'Binding' cannot be set on the 'Converter' property of type 'Binding'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject."

Is there a way to achieve this? Any help is appreciated.

Was it helpful?

Solution

The problem in this particular case is that the converter needs to access the window's DataContext,so I decided to implement it in the window's code behind

One option would be to make the IValueConverter it's own class, and create an instance in XAML as you normally would. If you make the converter a DependencyObject, you could add a dependency property for a UIElement, and bind the Window (myWindow) to the property. This would allow the converter to have access to the Window (via it's property) in order to fetch the DataContext.

The converter could just be referenced as normal within the binding in this design.

OTHER TIPS

I think MultiValueConverter can solve your problem: http://msdn.microsoft.com/en-us/library/system.windows.data.imultivalueconverter.aspx. In your situation, beside SomeProperty, you can pass DataContext of the window to the converter and do whatever you want.

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