コードを介して DataGrid を操作する必要はありません。代わりに、DataGrid の ItemsSource を ObservableCollection にバインドし、コレクションを操作します。DataGrid は自動的に更新されます。
ここを見てください:新しい値を割り当てた後、ObservableCollection を DataGrid にバインドする
実際、多くの場合 (私の場合は 95% の確率で)、WPF コントロールに名前を付けたくないことがわかります。コードが UI を認識していない場合、長期的には保守が容易になります。データ バインディングを介して UI に情報を取得する場所を知らせます。そして、INotifyPropertyChanged または Dependency Properties、および DataContext を見てください。
<DataGrid ItemsSource="{Binding MyCollection}" />
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
ObservableCollection<object> myCollection = new ObservableCollection<object>();
public ObservableCollection<object> MyCollection
{
get
{
return myCollection;
}
set
{
myCollection = value;
// Call the Notification here. Using linq and reflection you could get it to look like this:
// NotifyPropertyChanged(() => MyCollection);
}
}
myCollection 値を実際に変更しない場合は、変更通知を提供する必要はありません。ObservableCollection は、コレクションを変更すると、実際には独自の変更を提供します。