WPF数据网格没有得到更新
本文关键字:更新 数据 数据网 网格 WPF | 更新日期: 2023-09-27 18:11:39
我已经定义了一个数据网格如下:
<DataGrid Grid.Row="0" Grid.Column="0" x:Name="s" MaxHeight="300"
ItemsSource="{Binding MsgCollection, IsAsync=False, Mode=OneTime}">
<DataGrid.Columns>
<DataGridTextColumn x:Name="BankId"
Header="Bank Nr."
Binding="{Binding BankId}"
DisplayIndex="0" />
<DataGridTextColumn x:Name="MessageB"
Header="Message B"
Binding="{Binding MessageB}"
DisplayIndex="1" />
</DataGrid.Columns>
</DataGrid>
viewModel代码看起来像这样:
public class AwesomeDataViewModel : ViewModelBase
{
...
public ObservableCollection<Bank> MsgCollection
{
get
{
return m_Msgs;
}
set
{
m_Msgs = value;
OnPropertyChanged("MsgCollection");
}
}
AwesomeRandomMethode(){
...
// bankCollection contains 200 items
MsgCollection = new ObservableCollection<Bank>(bankCollection);
OnPropertyChanged("MsgCollection");
}
}
稍后在程序中调用AwesomeRandomMethode()
以将项目添加到dataGrid中。我通过调用OnPropertyChanged
通知更改,但没有发生任何变化。
我知道OnPropertyChanged
工作,因为我有一个按钮,利用它,它得到通知。
然而,如果我切换标签,突然数据网格得到更新!
我在寻找一个不违反MVVM原则的解决方案
你的问题是你的绑定,它应该是源项目的双向绑定。默认绑定是双向的,所以不要显式声明它。
<DataGrid Grid.Row="0" Grid.Column="0" x:Name="s" MaxHeight="300" ItemsSource="{Binding MsgCollection}">
</DataGrid>
你也应该有你的ObservableCollection已经声明和添加或删除项目。这样所有内容都会自动更新。
变化
ItemSource="{Binding MsgCollection, IsAsync=False, Mode=OneTime}"
ItemSource="{Binding MsgCollection, IsAsync=False, Mode=TwoWay}"
WPF绑定模式:https://stackoverflow.com/a/2305234/5147720