WPF IValueConverter - 将多个值转换为单个值

5
我现在正在维护别人的代码,那个人是WPF专家,而我不是。 :) 该代码使用IValueConverter将状态枚举值转换为布尔值,以控制屏幕上是否显示UserControl。 我发现一个缺点,单个枚举在这种情况下是不够的,还需要考虑另一个布尔值。 是否有另一个对象可以使用,需要将2个项作为参数进行转换?(“转换器”参数已经被使用。)一个快速的例子如下。现有代码的逻辑是...
If it's sunny, go to work.
If it's raining, don't go to work.

我需要考虑另一件事情,这会使它变成以下形式。
If it's sunny and you're wearing pants, go to work.
If it's sunny and you're not wearing pants, don't go to work.
If it's raining and you're wearing pants, don't go to work.
If it's raining and you're not wearing pants, don't go to work.

IValueConverter 只允许我将一个“东西”进行转换。任何帮助将不胜感激。谢谢,mj

1个回答

15

使用一个 IMultiValueConverter

public class MyMultiValueConverter: IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        // Do something with the values array. It will contain your parameters
    }

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

你还需要在XAML中使用MultiBinding而不是普通的绑定。

<MultiBinding Converter="{StaticResource MyMultiValueConverterKey}">
    <Binding Path="Value1" />
    <Binding Path="Value2" />
</MultiBinding>

我有一个问题。如何根据页面上两个文本框的非空值来启用/禁用按钮?我可以使用样式、IMultivalueConvertor,但如果文本框的数量不断变化/增加会怎么样?有没有一种动态监测来检查按钮行为的方法?你想让我单独提一个问题吗? - Vikram
1
@Vikram 最好提出一个单独的问题。很可能你想设置CanExecuteCommand,使其检查所有绑定字段的值,并仅在它们都有值时返回true。 - Rachel
非常感谢提供的信息。我已经成功实现了。 - Vikram

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接