Matthias
Matthias

Reputation: 280

WPF Binding, always create new object

In my model, I have the following property

public List<IColumnElement> MenuItems
{
  get
  {
    return new List<IColumnElement>() { new Table(), new FieldSet() };
  }
}

It is bound as Itemssource to a context menu and creates two elements "Table" and "FieldSet". If the element is clicked, the bound object shall be added to a collection. However the bound List is only generated once and always returns the same two objects....

Is there a good solution to make the binding always return new objects for Table and FieldSet ?

Upvotes: 0

Views: 572

Answers (1)

Tyler Lee
Tyler Lee

Reputation: 2785

WPF Binding generally occurs in response to change. When you first start up, the property is initially bound (the one time you see it), but until your code tells WPF that the property has changed, it's won't check again.

The way to tell WPF that the property has changed is through implementing INotifyPropertyChanged. Your class containing MenuItems would implement that interface, and then when you want WPF to call your getter again, you would invoke the PropertyChanged event, passing in the property name as a parameter.

As a matter of convenience, usually you would implement a base class that provide the interface, and a method such as

internal void RaisePropertyChanged(String propertyName)
{
    if (PropertyChanged != null)
    {
         PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}

You would then call RaisePropertyChanged("MenuItems"); in order to trigger a binding update.

As a side note, I would consider adjusting your design to just having the context menu list options, and have your code behind/view model take care of constructing the requisite objects when the corresponding option is chosen from the context menu.

Upvotes: 2

Related Questions