0
votes

I have a DataGrid witch is bound to a ObservableCollection<"Product">. The columns are bound to properties of Product. Most of then are of type double?(nullable).

In some time I have to set some property to null. After that, no matter the value I set, the binding don't work. The value is not updated in the view.

What happens to the binding when I set a property to null?

I tried what is shown in this blog post http://wildermuth.com/2009/11/18/Data_Binding_Changes_in_Silverlight_4 but it didn't worked to me.

Thanks!

Edit: Below is the class I've created that implements the 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);
    }
}    

This is my Product class. The DataGrid's ItemsSource property is bound to a ObservableCollection of 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);
        }
     }  
}

Look the Reset() method. The binding stop working after I call this method. In my app, I need that when the user press "Del" key, the DataGrid's row get empty, but can not be removed.

1
Please post your xaml and one of the property of your viewmodel - gaurawerma

1 Answers

1
votes

If you set the reference of the collection to null, the binding is broken between your control and source because the source doesn't exist anymore. In this case you have to explicitly rebind the items source in the control.

It is recommended to clear the collection instead of assigning null to it.

Update: For properties of items within the collection, make sure the item type implements INotifyPropertyChanged. The row in the DataGrid will be listening for changes through this interface on the item class itself.