man*_*nni 6 data-binding wpf datacontext converter ivalueconverter
我遇到了转换器的问题,我用它来转换字符串和我们的时间格式.转换器本身工作正常,并实现如下:
[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
}
}
Run Code Online (Sandbox Code Playgroud)
使用转换器的XAML在usercontrol.resources中包含转换器本身,如下所示:
<converter:StringToSimpleTimeConverter x:Key="stringToSimpleTimeConverter"/>
Run Code Online (Sandbox Code Playgroud)
如果遇到属性(我在后台使用wpf工具包中的datagrid),则使用用于编辑simpletime的datatemplate:
<DataTemplate x:Key="SimpleTimeEditingTemplate">
<TextBox Text="{Binding, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是转换器需要在绑定中指定路径,如果它是双向转换器(我需要在两个方向),但我想要设置的属性已经是当前的DataContext - 什么路径那我可以指定吗?
我能想到的唯一解决方法是在SimpleTime中引入一个虚拟属性,它只获取当前的SimpleTime或设置它.
public class SimpleTime
{
...
public SimpleTime Clone
{
get { return new SimpleTime(_amount, _format); }
set { this._amount = value._amount; this._format = value._format; }
}
}
Run Code Online (Sandbox Code Playgroud)
并绑定到那个通过
<TextBox Text="{Binding Clone, Converter={StaticResource stringToSimpleTimeConverter}, Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)
工作正常但不是真正合适的解决方案,特别是如果我需要转换器更多次...
任何帮助都赞赏欢呼,曼尼
我想你可以像这样解决它
<TextBox Text="{Binding Path=DataContext,
RelativeSource={RelativeSource Self},
Converter={StaticResource stringToSimpleTimeConverter},
Mode=TwoWay}"/>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6851 次 |
| 最近记录: |