首页 > 解决方案 > 尝试绑定此 ValueConverter 时出现“只能在 DependencyObject 的 DependencyProperty 上设置绑定”错误

问题描述

我有这堂课:

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”属性上设置“绑定”。只能在 DependencyObject 的 DependencyProperty 上设置“绑定”。

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

标签: c#wpfdata-bindingdependency-properties

解决方案


按照微软 CEO 的命令,我们需要遵循他在注册依赖属性时定义的命名约定。所以问题是你忘了敲几个键,正确的形式是:

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

推荐阅读