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

时间:2016-11-02 09:41:14

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

我有一个UserControl,其中包含2个自定义DependencyProperty s ColumnsCountRowsCount):

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
通过调试,我知道DataContext的{​​{1}}已正确设置

但是,当UserControl发生更改(=&gt;我选择了列表中的其他项目)时,我的SelectedRoom的{​​{1}} DependencyProperty未更新。 我非常沮丧,因为我已经花了一整天时间使用ColumnsCountUserControl之类的工具调试这个意想不到的事。 请帮忙。

编辑:
Clemens已经指出,XAMLSpy包裹WpfSpoonCLR-Property)的断点是未被解雇。这是一个主要问题,因为我必须在变更上调用一些方法。我正在尝试使用DependencyProperty,但我目前遇到了一些错误。

1 个答案:

答案 0 :(得分:1)

为了获得有关依赖项属性值更改的通知,您应该在注册属性时在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
}
相关问题