【问题标题】:"A binding can only be set on a DependencyProperty of a DependencyObject" error when attempting to bind this ValueConverter尝试绑定此 ValueConverter 时出现“只能在 DependencyObject 的 DependencyProperty 上设置绑定”错误
【发布时间】:2019-05-02 03:37:05
【问题描述】:

我有这门课:

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 上设置。

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

【问题讨论】:

  • 您正在注册“查找”属性...?应该是“LoopupList”。
  • 我知道这很简单。

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


【解决方案1】:

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

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

【讨论】:

  • 老实说,我认为 -Property 约定已经涵盖了这一点。
  • 是的。我认为它只是被新鲜的眼睛发现,有时我们看不到明显的东西;)有时
  • 通过使用 nameof 来避免这个问题:DependencyProperty.Register(nameof(LookupList), ...)
猜你喜欢
  • 2017-10-30
  • 2012-07-11
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2012-04-19
  • 2016-08-02
  • 2015-05-21
  • 1970-01-01
相关资源
最近更新 更多