【问题标题】:DataGrid not updating right awayDataGrid 没有立即更新
【发布时间】:2013-11-07 15:13:05
【问题描述】:

在我的程序中,我有一个通过 MVVM 实现的DataGrid。在这个DataGrid 旁边是一个按钮,它执行我命名为“Fill Down”的命令。它采用其中一列并将字符串复制到该列中的每个单元格。问题是视图不会进行更改,直到我更改页面然后返回到带有DataGrid 的页面。为什么会发生这种情况,我可以做些什么来解决它?

xaml:

<Button Command="{Binding FillDown}" ... />
<DataGrid ItemsSource="{Binding DataModel.Collection}" ... />

视图模型:

private Command _fillDown;

public ViewModel()
{
     _fillDown = new Command(fillDown_Operations);
}

//Command Fill Down
public Command FillDown { get { return _fillDown; } }
private void fillDown_Operations()
{
    for (int i = 0; i < DataModel.NumOfCells; i++)
    {
        DataModel.Collection.ElementAt(i).cell = "string";
    }
    //**I figured that Notifying Property Change would solve my problem...
    NotifyPropertyChange(() => DataModel.Collection);
}

-如果您想查看更多代码,请告诉我。

是的,抱歉我的收藏是ObservableCollection

【问题讨论】:

  • 你的收藏是 ObservableCollection 吗?
  • @Doc 没关系。 OP 没有从集合中添加/删除项目。
  • @HighCore 好点——我猜他需要通知每个元素的属性更改?

标签: c# wpf mvvm datagrid command


【解决方案1】:

在属性的设置器中调用 NotifyPropertyChanged():

public class DataItem
{
   private string _cell;
   public string cell //Why is your property named like this, anyway?
   {
       get { return _cell; }
       set
       {
           _cell = value;
           NotifyPropertyChange("cell");

           //OR

           NotifyPropertyChange(() => cell); //if you're using strongly typed NotifyPropertyChanged.
       }
   }
}

旁注:

改变这个:

for (int i = 0; i < DataModel.NumOfCells; i++)
{
    DataModel.Collection.ElementAt(i).cell = "string";
}

到这里:

foreach (var item in DataModel.Collection)
    item.cell = "string";

更简洁易读。

【讨论】:

  • 谢谢。我的属性仅在示例中命名为“单元格”。
猜你喜欢
  • 1970-01-01
  • 2017-05-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-11
  • 2020-10-09
相关资源
最近更新 更多