【问题标题】:Binding doesn't work after setting the property value to null将属性值设置为 null 后绑定不起作用
【发布时间】:2012-02-29 17:27:21
【问题描述】:

我有一个绑定到 ObservableCollection 的 DataGrid 女巫。这些列绑定到 Product 的属性。大多数都是双精度类型?(可为空)。

有时我必须将某些属性设置为空。之后,无论我设置什么值,绑定都不起作用。该值不会在视图中更新。

当我将属性设置为 null 时,绑定会发生什么情况?

我尝试了这篇博文 http://wildermuth.com/2009/11/18/Data_Binding_Changes_in_Silverlight_4 中显示的内容,但对我没有用。

谢谢!

编辑: 下面是我创建的实现 INotifyPropertyChanged 的​​类

public class NotifyPropertyChangedAttribute : INotifyPropertyChanged
{
    Dictionary<string, object> _propBag = new Dictionary<string, object>();
    protected object Get(string propName)
    {
        object value = null;
        _propBag.TryGetValue(propName, out value);
        return value;
    }

    protected void Set(string propName, object value)
    {
        if (!_propBag.ContainsKey(propName) || Get(propName)!=null)
        {
            _propBag[propName] = value;
            OnPropertyChanged(new PropertyChangedEventArgs(propName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
    {
        if (PropertyChanged != null)
        PropertyChanged(this, e);
    }
}    

这是我的产品类。 DataGrid 的 ItemsSource 属性绑定到产品的 ObservableCollection:

public class Product : NotifyPropertyChangedAttribute
{

    public string Name
    {
        get { return (string)Get("Name") ?? ""; }
        set { Set("Name", value); }
    }

    public double? Price
    {
        get {return (double)Get("Price") ?? null;}
        set { Set("Price", value);}
    }

    public void Reset()
    {
        var propertyInfo = typeof(Product).GetProperties(BindingFlags.DeclaredOnly     | BindingFlags.Public | BindingFlags.Instance);
        foreach (var p in propertyInfo)
        {
            p.SetValue(this , null, null);
        }
     }  
}

看看 Reset() 方法。调用此方法后绑定停止工作。 在我的应用程序中,我需要当用户按下“Del”键时,DataGrid 的行变空,但不能被删除。

【问题讨论】:

  • 请发布您的 xaml 和您的视图模型的属性之一

标签: silverlight silverlight-5.0


【解决方案1】:

如果将集合的引用设置为 null,则控件和源之间的绑定会中断,因为源不再存在。在这种情况下,您必须显式地重新绑定控件中的项目源。

建议清空集合而不是给它赋值。

更新:对于集合中项目的属性,请确保项目类型实现 INotifyPropertyChanged。 DataGrid 中的行将通过项目类本身的此接口侦听更改。

【讨论】:

  • 我没有将 null 设置为集合。我将 null 设置为集合项目的某些属性。还是一样?我必须再次设置绑定?谢谢!
  • 哦,对不起,我看错了你的问题。不,您不必重置绑定。您收藏的项目是否实现了 INotifyPropertyChanged?可能即使您的集合实现了它,但项目类型本身并没有因此将更改通知给 DataGrid。
  • 我创建了一个实现 INotifyPropertyChanged 的​​类,我的 Product 类继承自它。我已经更新了问题以显示一些代码。
猜你喜欢
  • 2012-10-12
  • 2011-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多