列出 DependencyProperty 始终返回 null

List DependencyProperty always returning null

我有一个具有以下 DependencyProperty 的自定义控件 "ToolbarMenuButton":

public ObservableCollection<object> TbMenuItems
{
    get { return (ObservableCollection<object>)GetValue(TbMenuItemsProperty); }
    set { SetValue(TbMenuItemsProperty, value); }
}

public static readonly DependencyProperty TbMenuItemsProperty =
    DependencyProperty.Register("TbMenuItems", typeof(ObservableCollection<object>), typeof(ToolbarMenuButton), new PropertyMetadata(null));

我是这样设置的:

<customs:ToolbarMenuButton TbText="By Flight" TbIcon="PlaneRotated45"
                           TbMenuItems="{Binding Flights}"
                           TbItemCommand="{Binding FlightSelect}">

它出现了,没问题。现在,自定义控件中的此按钮有一个单击处理程序,可确保设置上下文菜单,如果未设置,它会根据上面显示的依赖关系属性 "TbMenuItems" 创建一个新菜单.

错误: 此 属性 始终为 null(当我单击该按钮时,我在运行时得到一个 null 异常)。我已经通过大约 40 个关于此的 Whosebug 答案,它们要么 N/A 要么没有修复它。据我了解,get/set 不会调用依赖属性,但我不确定我应该如何从中获取数据。

我尝试过的: 我已经尝试在设置航班时通知 属性 更改。我已经通过将其中一个放在按钮旁边的文本块中来确保设置航班(所以我也知道数据上下文和路径等都是正确的)。我已将其更改为一个可观察的集合(最初是一个列表)以查看是否有帮助。其他依赖属性似乎都工作得很好(当然,它们也绑定到样式中的数据模板,不确定是否重要)。我现在不知道去哪里。

问题是您使用的集合类型过于具体 属性,它与数据绑定产生的值不兼容。

您应该改用最通用的集合类型,通常是 IEnumerable:

public IEnumerable TbMenuItems
{
    get { return (IEnumerable)GetValue(TbMenuItemsProperty); }
    set { SetValue(TbMenuItemsProperty, value); }
}

public static readonly DependencyProperty TbMenuItemsProperty = DependencyProperty.Register(
    nameof(TbMenuItems), typeof(IEnumerable), typeof(ToolbarMenuButton));