将属性值设置为null后,绑定不起作用

时间:2012-02-29 17:27:21

标签: silverlight silverlight-5.0

我有一个DataGrid女巫绑定到ObservableCollection<“Product”>。列绑定到Product的属性。大多数都是double型(可以为空)。

在某些时候,我必须将一些属性设置为null。之后,无论我设置的值如何,绑定都不起作用。该值未在视图中更新。

当我将属性设置为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的Products:

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的行变空,但无法删除。

1 个答案:

答案 0 :(得分:1)

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

建议清除集合,而不是为其指定null。

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

相关问题