尝试绑定此ValueConverter时发生错误“只能在DependencyObject的DependencyProperty上设置绑定”

时间:2018-11-30 00:58:37

标签: c# wpf data-binding dependency-properties

我上了这个课:

public class AssetDescriptionLookupConverter : FrameworkElement, IValueConverter
{
    public IEnumerable<T_AssetDescription> LookupList
    {
        get { return (IEnumerable<T_AssetDescription>)GetValue(LookupListProperty); }
        set { SetValue(LookupListProperty, value); }
    }

    public static readonly DependencyProperty LookupListProperty =
        DependencyProperty.Register("Lookup", typeof(IEnumerable<T_AssetDescription>),
        typeof(AssetDescriptionLookupConverter));

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        T_AssetDescription description = 
            LookupList.FirstOrDefault(x => x.AssetDescriptionID.Equals(value));
        if (description == null) return "";
        return description.Item;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}

当我尝试将其作为这样的资源包含在我的XAML中时:

<local:AssetDescriptionLookupConverter 
    x:Key="assetDescriptionLookup" 
    LookupList="{Binding AssetDescriptions}" />

我在LookupList="{Binding AssetDescriptions}"下弯曲成红色,并显示错误消息

  

不能在“ AssetDescriptionLookupConverter”类型的“ LookupList”属性上设置“ Binding”。只能在DependencyObject的DependencyProperty上设置“绑定”。

这是为什么?我该如何解决?

1 个答案:

答案 0 :(得分:1)

按照Microsoft CEO的命令,我们需要遵循他在注册依赖项属性时定义的命名约定。所以问题是您忘记按了几次击键,正确的格式是:

public static readonly DependencyProperty LookupListProperty =
    DependencyProperty.Register("LookupList", typeof(IEnumerable<T_AssetDescription>),
    typeof(AssetDescriptionLookupConverter));