使用UserControl的自定义依赖属性的数据绑定不起作用

本文关键字:数据绑定 不起作用 属性 自定义 UserControl 使用 依赖 | 更新日期: 2023-09-27 18:16:07

我有一个UserControl和2个自定义DependencyProperty s (ColumnsCount, RowsCount):

public partial class CabinetGrid : UserControl
{
    public static readonly DependencyProperty ColumnsCountProperty =
        DependencyProperty.Register("ColumnsCount", typeof (int), typeof (CabinetGrid));
    public static readonly DependencyProperty RowsCountProperty =
        DependencyProperty.Register("RowsCount", typeof (int), typeof (CabinetGrid));
    public int ColumnsCount
    {
        get { return (int) GetValue(ColumnsCountProperty); }
        set { SetValue(ColumnsCountProperty, value); }
    }
    public int RowsCount
    {
        get { return (int) GetValue(RowsCountProperty); }
        set { SetValue(RowsCountProperty, value); }
    }
}

这里是DataBinding:

<view:CabinetGrid Grid.Column="1" Grid.Row="2" x:Name="GridRack" ColumnsCount="{Binding SelectedRoom.ColumnCount}" />

而窗口的DataContext有一个属性SelectedRoom,它调用了PropertyChanged-Event
通过调试,我知道UserControlDataContext设置正确

但是,当SelectedRoom发生变化时(=>我在列表中选择了另一项),我的UserControlDependencyProperty ColumnsCount没有更新。我非常沮丧,因为我已经花了一整天的时间来调试这个意想不到的狗屎,使用XAMLSpyWpfSpoon等工具。请帮助。


编辑:
Clemens已经指出,在CLR-Property中包装DependencyProperty (ColumnsCount)的断点是未触发。这是一个主要问题,因为我必须在更改时调用一些方法。我试图使用PropertyChangedCallback,但我目前遇到一些错误。

使用UserControl的自定义依赖属性的数据绑定不起作用

为了获得依赖属性值更改的通知,您应该在注册该属性时在PropertyMetadata中指定PropertyChangedCallback。

public static readonly DependencyProperty ColumnsCountProperty =
    DependencyProperty.Register(
        "ColumnsCount", typeof(int), typeof(CabinetGrid),
         new PropertyMetadata(OnColumnsCountPropertyChanged));
private static void OnColumnsCountPropertyChanged(
    DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
     var cabinetGrid = (CabinetGrid)obj;
     // do something with the CabinetGrid instance
}