【问题标题】:DataContext not refreshed when changing object value更改对象值时未刷新 DataContext
【发布时间】:2013-02-05 06:37:22
【问题描述】:

我有一个grid,它的DataContext 是从后面的代码中分配的:

CustomerDataGrid.DataContext = _customerobj;

当某些函数正在执行时,_customerobj 对象会发生变化:

_customerobj = obj;

但DataContext 不会根据新对象的详细信息进行更新。如果我使用以下内容,它会更新:

_customerobj = obj;
CustomerDataGrid.DataContext = _customerobj;

每次 _customerobj 更新时我是否需要遵循相同的操作或者我错过了什么?

【问题讨论】:

  • 您的 _customerobj 的类型是否实现了 INotifyPropertyChanged? msdn.microsoft.com/en-us/library/…
  • 我想你想要一个绑定和 INotifyPropertyChanged
  • @Nathan- 不,它没有实现INotifyPropertyChanged。我需要实现它吗?
  • 实施INotifyPropertyChanged 不会解决这个问题。请看我的回答。

标签: c# .net wpf data-binding


【解决方案1】:

您遇到的情况不是由未实施INotifyPropertyChanged引起的。

当您执行CustomerDataGrid.DataContext = _customerobj; 时,您将DataContext 设置为某个值。之后你设置_customerobj = obj; 时,你只是给_customerobj 一个新值,但DataContext 仍然引用原始对象,所以它不会改变。

例如:

string a = "hello";
string b = a; // b points to "hello"
a = "world";  // a points to "world"
              // but b's pointer doesn't change

Console.WriteLine(b); // Outputs "hello"

这意味着您还必须设置 DataContext。

注意:这实际上不是字符串的工作方式,因为 .NET 字符串是不可变的,但希望这能说明问题。

【讨论】:

    【解决方案2】:

    @AdiLester 上面的回答是正确的,这就是发生这种情况的原因。
    也就是说,如果您宁愿只设置一次 DataContext,并且仍然在网格中更改对象,您可以 wrap 您的属性(例如在 ViewModel 中),将网格绑定到属性并那么当属性发生变化时,网格也会发生变化。

    例如:

    public class MyViewModel : INotifyPropertyChanged
    {
       private MyObj _customerObj;
       public MyObj CustomerObj
       {
           get { return _customerObj;}
           set
            {
                if (_customerObj != value)
                {
                    _customerObj = value;
    
                    if (PropertyChanged != null)
                    {
                        PropertyChanged(this, new PropertyChangedEventArgs("CustomerObj"));
                    }
                }
            }
       }
    }
    

    现在你可以这样做了:

     MyViewModel vm = new MyViewModel();
     vm.CustomerObj = //Whatever;
     CustomerDataGrid.DataContext = vm;
    

    当你绑定你的网格时,使用:{Binding CustomerObj}

    【讨论】:

      【解决方案3】:

      按照@Johan Larsson 的建议,您需要实现INotifyPropertyChanged 以让UI 知道数据已更改。

      This tutorial 以简单的方式详细说明了如何。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-09
        • 2017-08-14
        • 2016-09-08
        • 2021-02-24
        • 2014-03-09
        • 2010-09-16
        • 2014-08-01
        • 1970-01-01
        相关资源
        最近更新 更多