aicu
aicu

Reputation: 13

WPF binding update

Can anyone explain why I cannot use new to reset the binding data?

Using MVVM, the Data is binding to a ListBox.

The DataList already implements INotifyPropertyChanged.

In the method OnChange()

public void OnChange()
{
    data = new ObservableCollection<DataList>(); // not work
    data.Add(new DataList() { Text = "Changed 1" });
    data.Add(new DataList() { Text = "Changed 2" });
}

but

public void OnChange()
{
    data.Clear(); // works fine
    data.Add(new DataList() { Text = "Changed 1" });
    data.Add(new DataList() { Text = "Changed 2" });
}

The ViewModel

ObservableCollection<DataList> data;
public ObservableCollection<DataList> Data
{
    get { return data; }
    set { data = value; }
}

public ViewModel()
{
    this.Command_OnChange = new RelayCommand(ExecuteCommand1, CanExecuteCommand);

    data = new ObservableCollection<DataList>();
    data.Add(new DataList() { Text = "Default 1" });
    data.Add(new DataList() { Text = "Default 2" });
}

public void OnChange()
{
    data.Add(new DataList() { Text = "Changed 1" });
    data.Add(new DataList() { Text = "Changed 2" });
}

Upvotes: 1

Views: 163

Answers (1)

Sriram Sakthivel
Sriram Sakthivel

Reputation: 73442

Because when you change the backing field, there is no way that wpf could know about the change.

In fact you can overwrite the variable with new instance of ObservableCollection, but you have to implement INotifyPropertyChanged in your ViewModel class too.

private ObservableCollection<DataList> data;
public ObservableCollection<DataList> Data
{
    get { return data; }
    set 
    { 
        data = value;
        OnPropertyChanged("Data");
    }
}

And in your OnChange method

public void OnChange()
{
    Data = new ObservableCollection<DataList>();//Note the use of Data property not field
    Data.Add(new DataList() { Text = "Changed 1" });
    Data.Add(new DataList() { Text = "Changed 2" });
}

Upvotes: 1

Related Questions