私は、プロジェクトを明示するためにWPFプロジェクトを作成しました。NotifyOfPropertyChangeがDataGridでトリガーされていません
免責事項:私はPropertyChangedBase
とBindableCollection
を使用する場合にのみCaliburn.Microを使用しています。このプロジェクトの他のすべては、定型的なWPFのものです。
右のように、クラスはDataItem
です。 Qty
呼ば
int
、そして- が
Qty
のダブルですSum
と呼ばれる計算されたプロパティ、:それはちょうど2つのプロパティを持っています。
これだけです。わかりやすくするために、コードは次のとおりです。
public class DataLine : PropertyChangedBase
{
private int qty;
public int Qty
{
get
{
return qty;
}
set
{
if (value == qty)
{
return;
}
qty = value;
NotifyOfPropertyChange();
NotifyOfPropertyChange(() => Sum);
}
}
public int Sum => qty * 2;
public DataLine(int a)
{
Qty = a;
}
}
今、ViewModelです。それはDataLines
のすべてSum
を追加し、
DataLine
のBindableCollection
(ObservableCollection
のカリバーンの味である)、int
- を持っています。
のICommandはBindableCollection
とint
のトリガーNotifyPropertyChanged
が、何もしません。 View
のために、今すぐ
class ViewModel: PropertyChangedBase
{
public ViewModel()
{
Data = new BindableCollection<DataLine>
{
new DataLine(1),
new DataLine(2),
new DataLine(4),
new DataLine(6)
};
RefreshCommand = new RefreshCommand(this);
}
private BindableCollection<DataLine> _data;
public BindableCollection<DataLine> Data
{
get
{
return _data;
}
set
{
if (value == _data)
{
return;
}
_data = value;
NotifyOfPropertyChange();
NotifyOfPropertyChange(() => Amount);
}
}
public ICommand RefreshCommand { get; private set; }
public void RefreshAction()
{
NotifyOfPropertyChange(() => Data);
NotifyOfPropertyChange(() => Amount);
}
public int? Amount => Data?.Sum(c => c.Sum);
}
:
は、ここでは、コードです それは非常に簡単です。
BindableCollection
にバインドされたDataGrid
があります。Button
があり、ICommand
にバインドされています。- 「テキストボックス
, bound to
金額」があります。
ここView
のボディです:
<DockPanel>
<TextBox DockPanel.Dock="Bottom" Text="{Binding Amount, TargetNullValue='', Mode=OneWay}"/>
<Button DockPanel.Dock="Bottom" Command="{Binding RefreshCommand}" Content="Refresh"/>
<DataGrid ItemsSource="{Binding Data, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="True"/>
</DockPanel>
私はそれを実行すると、私はこのような何かを得る:
今トリッキーな部分が来る - 私はちょうど編集してみましょう行の1つ。
は、明瞭にするために、私は私のカーソルがDataGrid
を編集した後だった場所を示すために矢印が追加されました。最初の行のSum
がどのように更新されているかを確認しますが、画面下部のAmount
は同じままです。私はRefresh
をクリックしたときに
は今、これが起こる:
Amount
が正しく更新されます。
最終的に私の質問につながります。DataGrid
の何が問題なのですか?行が編集されたときにDataGrid
がそのセッターをトリガーしないのはなぜですか?そして、どのようにトリガーされていることを確認することができますか?
BindableCollection内のオブジェクトのプロパティを変更すると、コレクションプロパティ自体が魔法のように変更されることが予想されますか?コレクションエレメントを編集するだけで、データセッターは呼び出されません。だから、 "DataGridの何が問題なの?"何も、あなたの間違った期待です。 – Clemens
子オブジェクトのいずれかが編集されたときにコレクション自体に 'NotifyOfPropertyChange()'を呼び出す方法はありますか? –
もちろん、DataLineは何らかの形で親ビューモデルにアクセスでき、 'NotifyOfPropertyChange()=> Amount)'メソッドを呼び出すことができます。 – Clemens