9

DataGridがより多くの行を取得するか、一部が削除されるたびに、物事を再計算したいと思います。イベントを使おうとしたのLoadedですが、一度だけ解雇されました。

私は見つけましAddingNewItemた、しかしそれはそれが追加される前に解雇されます。後で自分のことをする必要があります。

動作するものもありLayoutUpdatedますが、私の目的にはあまりにも頻繁に発火するため、使用するのは賢明ではないのではないかと思います。

4

7 に答える 7

11

あなたDataGridが何かに縛られているなら、私はこれを行う2つの方法を考えています。

コレクションを取得して、そのイベントDataGrid.ItemsSourceをサブスクライブすることができます。CollectionChangedこれは、そもそもコレクションのタイプがわかっている場合にのみ機能します。

// Be warned that the `Loaded` event runs anytime the window loads into view,
// so you will probably want to include an Unloaded event that detaches the
// collection
private void DataGrid_Loaded(object sender, RoutedEventArgs e)
{
    var dg = (DataGrid)sender;
    if (dg == null || dg.ItemsSource == null) return;

    var sourceCollection = dg.ItemsSource as ObservableCollection<ViewModelBase>;
    if (sourceCollection == null) return;

    sourceCollection .CollectionChanged += 
        new NotifyCollectionChangedEventHandler(DataGrid_CollectionChanged);
}

void DataGrid_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    // Execute your logic here
}

もう 1 つの解決策は、Microsoft PrismEventAggregatorや MVVM Lightなどのイベント システムを使用することMessengerです。これは、バインドされたコレクションが変更されるたびにイベント メッセージViewModelをブロードキャストし、サブスクライブしてこれらのメッセージを受信し、メッセージが発生するたびにコードを実行することを意味します。DataCollectionChangedView

使用するEventAggregator

// Subscribe
eventAggregator.GetEvent<CollectionChangedMessage>().Subscribe(DoWork);

// Broadcast
eventAggregator.GetEvent<CollectionChangedMessage>().Publish();

使用するMessenger

//Subscribe
Messenger.Default.Register<CollectionChangedMessage>(DoWork);

// Broadcast
Messenger.Default.Send<CollectionChangedMessage>()
于 2012-07-02T14:04:04.150 に答える
2

どうDataGrid.LoadingRow(object sender, DataGridRowEventArgs e)ですか?

アンロードについても同じです。

DataGrid.UnLoadingRow(object sender, DataGridRowEventArgs e)

于 2012-07-02T12:24:41.187 に答える
2

MVVM アプローチと Observable コレクションへのバインディングを試しましたか?

public ObservableCollection<Thing> Items{
get { return _items; }
set{ _items = value; RaisePropertyChanged("Items");  // Do additional processing here 
}
}

UIに縛られずにアイテムの追加・削除を見れるように?

于 2012-07-02T14:07:36.580 に答える
0

ObservableCollection を使用して、追加または別の操作に関する通知を受け取りたい場合は、INotifyCollectionChanged を使用するのが最善の方法です。

var source = datagrid.ItemsSource as INotifyCollectionChanged;

に展開するときはObservableCollection<MyClass>()、MyClass (not ObservableCollection<ParentOfMyClass>())をストロングに記述する必要があるためです。

于 2015-06-26T15:13:08.087 に答える