【问题标题】:WPF - Getting PropertyName in IValueConverterWPF - 在 IValueConverter 中获取 PropertyName
【发布时间】:2010-05-27 18:14:32
【问题描述】:

我正在玩 WPF 和数据绑定,我想知道以下问题。 我定义了一些 PropertyGroupDescriptions,但现在我想知道如何从 IValueConverter 中读取 PropertyName。 这可能吗?

【问题讨论】:

  • 你的用途是什么?你要传递给转换器什么?
  • 它在 DataGrid 中用于分组。我想根据其属性调整标题
  • 这不像我预期的那样工作,太糟糕了:(

标签: c# ivalueconverter


【解决方案1】:

你不能。 IValueConverter interface 没有任何获取正在转换的属性的方法。

PropertyInfoPropertyDescriptor 实例传递给ConvertConvertBack 方法可能会很好,但设计人员认为没有必要。

解决这个问题的唯一方法是在代码中设置 IValueConverter 实现,然后在实现的构造中,您可以传递 IValueConverter 接口实现所附加到的属性。

【讨论】:

  • 我只是从属性组描述中引用转换器
  • 哪个不能作为 id 工作,您能否详细说明您的解决方案?
  • @Oxymoron:您必须通过代码来完成,并使用实现 IValueConverter 的类上的属性来指示您正在使用值转换器的属性。
【解决方案2】:

总是有通过绑定的 ConverterParameter 传递名称的廉价方式,尽管这并不是一种“干净”的方式。

【讨论】:

    【解决方案3】:

    也许我应该详细说明一下。我的 xaml 中有以下组:

    <CollectionViewSource x:Key="cvsTasks" Source="{StaticResource tasks}" Filter="CollectionViewSource_Filter" >            
                <CollectionViewSource.GroupDescriptions>
                    <PropertyGroupDescription PropertyName="ProjectName" />
                    <PropertyGroupDescription PropertyName="TaskName" />
                    <PropertyGroupDescription PropertyName="Complete" />
                </CollectionViewSource.GroupDescriptions>
    

    <TextBlock FontWeight="Bold" Text="{Binding Path=Name}"/>
    

    现在我想要一个转换器在 Name 上使用,这很好,但我只希望它在属性 Complete 上实际工作。最好的方法是什么?

    我最终得到了如下丑陋的代码:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                if (value != null)
                {
                    if (value.GetType().Equals(typeof(Boolean)))
                    {
                        return (bool)value ? "Complete" : "Active";
                    }
                    if (value.GetType().Equals(typeof(String)))
                    {
                        return value as string;
                    }
                }
                return null;
            }
    

    好像错了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多