Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using IValueConverter with current DataContext in two-way binding

I'm having issues with a converter i'm using to convert between a string and our timeformat. The converter itself works fine and is implemeneted like this:

    [ValueConversion(typeof(string), typeof(SimpleTime))]
    public class StringToSimpleTimeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // convert from string to SimpleTime and return it
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // convert value from SimpleTime to string and return it
        }
    }

The XAML that uses the converter includes the converter itself in the usercontrol.resources like this:

<converter:StringToSimpleTimeConverter x:Key="stringToSimpleTimeConverter"/>

If the property is encountered (I'm using the datagrid from the wpf toolkit in the background) the datatemplate for editing the simpletime is used:

<DataTemplate x:Key="SimpleTimeEditingTemplate">
        <TextBox Text="{Binding, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
</DataTemplate>

The problem i'm encountering is that the converter needs to have a path specified in the binding if it is a twoway converter (and i need it in both directions), but the property i want to set is already the current DataContext - What Path can i specify for that then?

The only workaround i could think of is introduce a dummy property in the SimpleTime that just gets the current SimpleTime or sets it.

public class SimpleTime
{
    ...
    public SimpleTime Clone
    {
        get { return new SimpleTime(_amount, _format); }
        set { this._amount = value._amount; this._format = value._format; }
    }
}

and bind to that one via

 <TextBox Text="{Binding Clone, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>

that works fine but isn't really a suitable solution, especially if i need converters for more times...

any help is appreciated cheers, manni

like image 844
manni Avatar asked Dec 10 '10 08:12

manni


1 Answers

I think you can workaround it like this

<TextBox Text="{Binding Path=DataContext,
                        RelativeSource={RelativeSource Self},
                        Converter={StaticResource stringToSimpleTimeConverter}, 
                        Mode=TwoWay}"/>
like image 127
Fredrik Hedblad Avatar answered Nov 19 '22 00:11

Fredrik Hedblad