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=TwoWa开发者_如何学Goy}"/>
</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
I think you can workaround it like this
<TextBox Text="{Binding Path=DataContext,
RelativeSource={RelativeSource Self},
Converter={StaticResource stringToSimpleTimeConverter},
Mode=TwoWay}"/>
Instead of introducing a dummy property into your class, why not create a container class like the following:
public class Container
{
public Object DataItem { get; set; }
//...
}
and use it like:
<TextBox Text="{Binding DataItem, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
This will not corrupt/mutate your existing class and still allow you to do what you wish to do.
I know it's old question, but in case somebody stumbles upon this, correct Path here would be Path=.
<DataTemplate x:Key="SimpleTimeEditingTemplate">
<TextBox Text="{Binding Path=., Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
</DataTemplate>
精彩评论