【问题标题】:WPF IValueConverter - converting multiple values into a single valueWPF IValueConverter - 将多个值转换为单个值
【发布时间】:2010-10-20 16:17:53
【问题描述】:

我现在正在尝试维护其他人的代码,该人是 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

【问题讨论】:

    标签: c# .net wpf ivalueconverter


    【解决方案1】:

    使用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 最好单独提出一个问题。您很可能希望设置 CanExecuteCommand 以便它检查所有绑定字段的值,并且仅在它们都有值时才返回 true。
    • 非常感谢您的信息。我能够做到。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-13
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-07-23
    • 1970-01-01
    • 2016-02-22
    相关资源
    最近更新 更多