2

我写了一个转换器 BoolToStringConverter。转换器有两个属性 TrueString 和 FalseString。这是我在 XAML 中使用它的方式

<UserControl.Resources>
    <local:BooleanToStringConverter x:Key="BooleanToStringConverter" TrueString="{Binding Strings.Open, Source={StaticResource MyStrings}}"></local:BooleanToStringConverter>
</UserControl.Resources>

这可以编译,但是在运行它时出现 xml 解析异常。如果我将 TrueString 属性的设置更改为 TrueString = "Open",则一切正常。

这是正在使用的转换器:

<Button x:Name="MyButton" Content="{Binding Path=IsOpen, Converter={StaticResource BooleanToStringConverter}}" Command="{Binding MyCommand}" VerticalAlignment="Top" Style="{StaticResource MyStyle}" Margin="0,2,10,2"/>

有什么想法有什么问题吗?我想做的就是将本地资源的属性设置为本地化值。

编辑这是我的转换器类

public class BooleanToStringConverter : IValueConverter
{
    public BooleanToStringConverter()
    {
    }

    public string TrueString
    {
        get;
        set;
    }

    public string FalseString
    {
        get;
        set;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool boolValue = System.Convert.ToBoolean(value, CultureInfo.InvariantCulture);

        return boolValue ? TrueString : FalseString;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }     
}

这是运行时异常消息:

System.Windows.dll 中出现“System.Windows.Markup.XamlParseException”类型的第一次机会异常

附加信息:设置属性“Optimize.Client.Presentation.BooleanToStringConverter.FalseString”引发异常。[行:18 位置:86]

4

2 回答 2

1

您不能绑定到TrueStringandFalseString属性。从MSDN 帮助

为了成为绑定的目标,属性必须是依赖属性

您可以尝试为您的 xaml 使用绑定的 ConverterParameter 部分

<Button x:Name="MyButton" Content="{Binding Path=IsOpen, Converter={StaticResource BooleanToStringConverter}, ConverterParameter=Open}" 
        Command="{Binding MyCommand}" VerticalAlignment="Top" 
        Style="{StaticResource MyStyle}" Margin="0,2,10,2"/>

您还可以使您的转换器不那么通用,只处理打开/关闭字符串。

另一种选择是让您的值转换器扩展 DependencyObject,并将您的属性转换为 DependencyProperties。

于 2012-06-27T22:08:20.153 回答
0

您还可以像这样在 XAML 中设置公共属性:

<localHelpers:BoolToTextConverter x:Key="boolToTextConverter">
    <localHelpers:BoolToTextConverter.TrueText>
        Sent
    </localHelpers:BoolToTextConverter.TrueText>
    <localHelpers:BoolToTextConverter.FalseText>
        Not Sent
    </localHelpers:BoolToTextConverter.FalseText>
</localHelpers:BoolToTextConverter>

完整的示例在我的博客文章中。

于 2013-08-19T16:46:22.543 回答