我想设置一个绑定。问题是目标是 string 类型,但源是 double 类型。
在以下代码中,VersionNumber 的类型为 double。当我运行它时,文本块是空的,没有抛出任何异常。
我该如何设置这个绑定?
<Style TargetType="{x:Type MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MyControl}">
<TextBlock Text="{TemplateBinding Property=VersionNumber}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
你需要一个转换器:
namespace Jahedsoft
{
[ValueConversion(typeof(object), typeof(string))]
public class StringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value == null ? null : value.ToString();
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
现在你可以像这样使用它:
<ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:j="clr-namespace:Jahedsoft">
<j:StringConverter x:Key="StringConverter" />
</ResourceDictionary>
...
<Style TargetType="{x:Type MyControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type MyControl}">
<TextBlock Text="{TemplateBinding Property=VersionNumber, Converter={StaticResource StringConverter}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)