如何将整数传递给ConverterParameter?

ako*_*nsu 88 wpf binding ivalueconverter

我想绑定到一个整数属性:

<RadioButton Content="None"
             IsChecked="{Binding MyProperty,
                         Converter={StaticResource IntToBoolConverter},
                         ConverterParameter=0}" />
Run Code Online (Sandbox Code Playgroud)

我的转换器是:

[ValueConversion(typeof(int), typeof(bool))]
public class IntToBoolConverter : IValueConverter
{
    public object Convert(object value, Type t, object parameter, CultureInfo culture)
    {
        return value.Equals(parameter);
    }

    public object ConvertBack(object value, Type t, object parameter, CultureInfo culture)
    {
        return value.Equals(false) ? DependencyProperty.UnsetValue : parameter;
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,当我的转换器被调用时,参数是字符串.我需要它是一个整数.当然我可以解析字符串,但我必须这样做吗?

感谢konstantin的任何帮助

jpi*_*son 99

你去吧!

<RadioButton Content="None"
             xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <RadioButton.IsChecked>
        <Binding Path="MyProperty"
                 Converter="{StaticResource IntToBoolConverter}">
            <Binding.ConverterParameter>
                <sys:Int32>0</sys:Int32>
            </Binding.ConverterParameter>
        </Binding>
    </RadioButton.IsChecked>
</RadioButton>
Run Code Online (Sandbox Code Playgroud)

诀窍是包括基本系统类型的命名空间,然后至少以元素形式编写ConverterParameter绑定.

  • @djacobson - True,但这是ValueConversion属性允许您指定的内容.不确定这是否真的在编译时或运行时使用.就原始海报问题而言,他指出"我需要它是一个整数.当然我可以解析字符串,但我必须这样做吗?" 所以我的答案减轻了,因为没有解析字符串,只有整数的解包,我仍然更安全. (5认同)
  • 这并没有改变`IValueConverter.Convert()`的*"参数"*参数的类型是`object`这一事实.你仍然需要演员/解析它...... (2认同)

Vla*_*lad 46

为了完整性,还有一个可能的解决方案(可能更少打字):

<Window
    xmlns:sys="clr-namespace:System;assembly=mscorlib" ...>
    <Window.Resources>
        <sys:Int32 x:Key="IntZero">0</sys:Int32>
    </Window.Resources>

    <RadioButton Content="None"
                 IsChecked="{Binding MyProperty,
                                     Converter={StaticResource IntToBoolConverter},
                                     ConverterParameter={StaticResource IntZero}}" />
Run Code Online (Sandbox Code Playgroud)

(当然,Window可以替换为UserControl,并且IntZero可以更接近实际使用地点.)


Gle*_*den 35

不确定为什么WPF人们倾向于不愿意使用MarkupExtension.它是许多问题的完美解决方案,包括此处提到的问题.

public sealed class Int32Extension : MarkupExtension
{
    public Int32Extension(int value) { this.Value = value; }
    public int Value { get; set; }
    public override Object ProvideValue(IServiceProvider sp) { return Value; }
};
Run Code Online (Sandbox Code Playgroud)

如果此标记扩展名在XAML命名空间"m"中可用,则原始海报的示例将变为:

<RadioButton Content="None"
             IsChecked="{Binding MyProperty,
                         Converter={StaticResource IntToBoolConverter},
                         ConverterParameter={m:Int32 0}}" />
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为标记扩展解析器可以看到构造函数参数的强类型并相应地进行转换,而Binding的ConverterParameter参数是(信息量较少)对象类型.