I have a very simple DependencyProperty example that I registered with a UserControl that does not work as expected.
I bind this property to a DP (called Test) in MainWindow, which seems to OnPropertyChanged events every time it changes, but the DependencyProperty in my UserControl, which is the object of this binding, only seems to get notified when this property changes for the first time.
Here is what I am trying to do in the code:
My UserControl:
public partial class UserControl1 : UserControl { public static readonly DependencyProperty ShowCategoriesProperty = DependencyProperty.Register("ShowCategories", typeof(bool), typeof(UserControl1), new FrameworkPropertyMetadata(false, OnShowsCategoriesChanged)); public UserControl1() { InitializeComponent(); } public bool ShowCategories { get { return (bool)GetValue(ShowCategoriesProperty); } set { SetValue(ShowCategoriesProperty, value); } } private static void OnShowsCategoriesChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
MainWindow.xaml.cs
public partial class MainWindow : Window, INotifyPropertyChanged { public MainWindow() { InitializeComponent(); Test = true; //this call changes default value of our DP and OnShowsCategoriesChanged is called correctly in my UserControl Test = false; //these following calls do nothing!! (here is where my issue is) Test = true; } private bool test; public bool Test { get { return test; } set { test = value; OnPropertyChanged("Test"); } } public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(string property) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(property)); } } }
MainWindow.xaml
<Window x:Class="Binding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:uc="clr-namespace:Binding" DataContext="{Binding RelativeSource={RelativeSource Self}}" Title="MainWindow" Height="350" Width="525"> <Grid> <uc:UserControl1 ShowCategories="{Binding Test}" /> </Grid> </Window>
genus source share