I'm having some trouble updating a dependency property of a UserControl/View.
I have a main view (MainView.xaml) that has a series of other user controls declared inside it. One of them looks as follows:
<local:Snapshot BrandID="{Binding Path=Session.Test}" />
My Snapshot.xaml has a a TextBlock:
<TextBlock Text="Sample text" x:Name="brandIDTBlock" />
And my Snapshot.xaml.cs has the following dependency property:
public string BrandID
{
get { return (string)GetValue(BrandIdProperty); }
set { SetValue(BrandIdProperty, value); }
}
public static readonly DependencyProperty BrandIdProperty = DependencyProperty.Register("BrandID", typeof(string), typeof(Snapshot), new PropertyMetadata(new PropertyChangedCallback(OnBrandIdChange)));
private static void OnBrandIdChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var control = (Snapshot)d;
control.brandIDTBlock.Text = (string)e.NewValue;
}
Session is a property of the MainView and I want my brandIDTBlock TextBlock to be updated when the Test property is changed in the Session object.
The Test property is declared like so:
private string _test = "Test Value Binding";
public string Test
{
get { return _test; }
set { _test = value; }
}
Right now somehting is working as when I run the app I see "Test Value Binding" correctly being displayed in my view, the problem is that when the value of Test changes in my Session object the change does not propagate to the view.
I also tried to implement the INotifyPropertyChanged interface like so:
public string Test
{
get { return _test; }
set
{
_test = value;
OnPropertyChanged("Test");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
but it's still not updating.
UPDATE: It turns out that it was a nooby mistake, again. In my Snapshot.xaml.cs I was changing the data context in a piece code that handled a pie chart. I worked around it by changing my binding epression in so that the binding element would be the parent of Snapshot.xaml, in my case the StackPanel 'sp' ({Binding ElementName=sp, Path=DataContext.Session.Test}). Apart from this silly mistake, what was really missing from my original code was the INotifyPropertyChanged implementation, TwoWay binding was unnecessary.
Thanks
Luis
INotifyPropertyChangedto theclass Sessiondeclaration line? - AnthonyWJones