DependencyProperty に問題があります。DependencyProperty をデフォルトとして設定したもの以外に設定できませんDependencyProperty.Register(...)
DataGrid を含む UserControl があります。UserControl には、ビジネス オブジェクトのコレクションを受け入れる DependencyProperty があります。UserControl の DataGrid の ItemsSource を DependencyProperty を介して設定したいと考えています。
私の 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;
}
1 つの UserControl を含み、コントロールの DependencyProperty を BObjectCollection (BindingList を拡張する) に設定する MainWindow があります。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 に 3 つの項目を含む BObjectCollection を作成しても、UserControl の BObjectCollection が空であることです。ブレークポイントを設定して何が起こっているかを確認すると、RowsCoerce のブレークポイントだけがトリップnewValue
し、3 つのアイテムを含む BObjectCollection ではなく、空の BObjectCollection になります。Rows の getter と setter のブレークポイント、および RowsChanged メソッドがトリップすることはありません。
UserControl が 3 つのアイテム (MainWindow で作成したアイテム) を含む BObjectCollection を受信しない理由がわかりません。ここで私は何を間違えましたか?DependencyProperty を間違って設定しましたか? DependencyProperties の経験はほとんどありません。
コードの壁で申し訳ありませんが、この質問をする簡単な方法がわかりません。