I have the following class as my DataContext
of my UserControl
:
public class ModelBase<T> : INotifyPropertyChanged where T : class
{
public T Model { get; set; }
public void UpdateUI()
{
OnPropertyChanged(string.Empty);
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
I am setting Model
as an arbitrary class the contains primitive types.
I seem to have the binding done correctly, because I can see that the properties are being populated as I change them in the UI.
But the problem is that when I change the properties from code behind, it won't update the view with it, even after calling UpdateUI()
. I verified the properties in the DataContext
of the UI (with WPF/XAML inspection software) and they have the correct values.
I believe it has something to do with the fact that it's a nested class inside the DataContext
, because I tried adding properties to ModelBase
to test it, and the bindings worked fine when I called UpdateUI()
.
I'm creating the controls/bindings and adding it to the UserControl
in the code behind, I'm not sure if this would cause a problem:
var textBox = new TextBox();
// Setup Binding
var binding = new Binding
{
Source = myModelBase.Model,
Path = new PropertyPath(nameOfProperty),
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
BindingOperations.SetBinding(textBox, TextBox.TextProperty, binding);
myUserControl.Content.Children.Add(textBox);