我的UserControl的DependencyProperty没有被设置

时间:2013-05-03 17:09:39

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

我遇到了DependencyProperty的问题。我无法将DependencyProperty设置为除DependencyProperty.Register(...)

中设置的默认值以外的任何其他属性

我有一个包含DataGrid的UserControl。 UserControl有一个DependencyProperty,它接受一组业务对象。我希望通过我的DependencyProperty设置UserControl中DataGrid的ItemsSource。

UserControl.xaml中的DataGrid是:

<DataGrid ItemsSource="{Binding Rows}" AutoGenerateColumns="True" />

我的UserControl.xaml.cs代码是:

public MyGrid()
{
    InitializeComponent();
    this.DataContext = this;
}

public BObjectCollection Rows
{
    get { return (BObjectCollection)GetValue(RowsCustomProperty); /* never gets called */ }
    set { SetValue(RowsCustomProperty, value); /* never gets called */ }
}
public static DependencyProperty RowsCustomProperty = DependencyProperty.Register("Rows", typeof(BObjectCollection), typeof(MyGrid), new PropertyMetadata(new BObjectCollection(), RowsChanged, RowsCoerce));

private static void RowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    MyGrid tab = (MyGrid)d; //never gets called
}

private static object RowsCoerce(DependencyObject d, object value)
{
    MyGrid tab = (MyGrid)d;
    BObjectCollection newValue = (BObjectCollection)value;
    return newValue;
}

我有一个包含一个UserControl的MainWindow,并将控件的DependencyProperty设置为BObjectCollection(扩展了BindingList)。 MainWindow.xaml代码很简单:

<local:MyGrid Rows="{Binding Rows}" />

我的MainWindow.xaml.cs是:

public MainWindow()
{
    this._rows = new BObjectCollection();
    this._rows.Add(new BObject("AAA", 10));
    this._rows.Add(new BObject("BBB", 20));
    this._rows.Add(new BObject("CCC", 30));

    this.DataContext = this;
    InitializeComponent();
}

private readonly BObjectCollection _rows;
public BObjectCollection Rows { get { return this._rows; } }

我的问题是,虽然我在MainWindow中创建了一个带有三个项目的BObjectCollection,但我的UserControl中的BObjectCollection是空的。当我设置断点以查看正在发生的事情时,只有RowsCoerce中的断点跳闸,而newValue是一个空的BObjectCollection,而不是一个包含三个项目的BObjectCollection。我在Rows getter和setter中的断点以及RowsChanged方法永远不会跳转。

我无法弄清楚为什么UserControl永远不会收到包含三个项目的BObjectCollection(我在MainWindow中创建的那个)。我在这做错了什么?我是否错误地设置了DependencyProperty?我对DependencyProperties的经验很少。

对于代码墙感到抱歉,但我不知道提问这个问题的简单方法。

1 个答案:

答案 0 :(得分:1)

您正在Rows中为UserControl分配绑定,但之后您将DataContext的{​​{1}}设置为自己。因此,绑定将解析为UserControl的{​​{1}}属性,而不是Rows上的UserControl属性。

Rows上设置Window通常是个坏主意。而是将其设置在DataContext的可视树中,如下所示:

UserControl