如何在WPF中将字符串绑定为double?

2 wpf binding

我想设置一个绑定.问题是目标是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>
Run Code Online (Sandbox Code Playgroud)

CSh*_*per 5

你需要一个转换器:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在您可以像这样使用它:

<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>
Run Code Online (Sandbox Code Playgroud)