【问题标题】:WPF Datagrid does not get updatedWPF Datagrid 未更新
【发布时间】:2015-12-04 06:11:40
【问题描述】:

我已经定义了一个数据网格如下:

<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() 将项目添加到数据网格中。 我通过调用OnPropertyChanged 通知更改,但没有任何反应。

我知道OnPropertyChanged 有效,因为我有一个按钮可以使用它并得到通知。

但是,如果我切换选项卡,数据网格会突然更新!

我正在寻找不违反 MVVM 原则的解决方案

【问题讨论】:

    标签: c# wpf mvvm datagrid


    【解决方案1】:

    您的问题是您的绑定,它应该是对源项目的双向绑定。默认绑定是 TwoWay,所以不要显式声明它。

    <DataGrid Grid.Row="0" Grid.Column="0" x:Name="s" MaxHeight="300" ItemsSource="{Binding MsgCollection}">
    </DataGrid>
    

    您还应该只声明您的 ObservableCollection 并添加或删除项目。这样,所有内容都会自动更新。

    【讨论】:

    • 该死的,我花了几个小时来解决这个愚蠢的“Mode=TwoWay”谢谢,
    • 这发生在我们最好的人身上。
    【解决方案2】:

    改变

    ItemSource="{Binding MsgCollection, IsAsync=False, Mode=OneTime}"
    

    为

    ItemSource="{Binding MsgCollection, IsAsync=False, Mode=TwoWay}"
    

    WPF 绑定模式:https://stackoverflow.com/a/2305234/5147720

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2012-09-01
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-03
      • 2018-10-26
      • 1970-01-01
      相关资源
      最近更新 更多