Hello everyone, I encountered such a problem
I have a window with resources

DataContext="{Binding RelativeSource={RelativeSource Self}}"> <Window.Resources> <my:MyClass x:Key="Key" MyProperty="{Binding Path=MyProp1}" MyProp2="{Binding Path=MyProp2}"/> </Window.Resources> 

All properties are propdp properties.

 public class MyClass: FrameworkElement { public int MyProperty { get { return (int)GetValue(MyPropertyProperty); } set { SetValue(MyPropertyProperty, value); } } // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), new UIPropertyMetadata(0)); public int MyProp2 { get { return (int)GetValue(MyProp2Property); } set { SetValue(MyProp2Property, value); } } // Using a DependencyProperty as the backing store for MyProp2. This enables animation, styling, binding, etc... public static readonly DependencyProperty MyProp2Property = DependencyProperty.Register("MyProp2", typeof(int), typeof(MainWindow), new UIPropertyMetadata(0)); } 

Why does data binding not work?

  • one
    Why is the second property owner type the typeof (MainWindow)? - andreycha

1 answer 1

Let's do archeology :)

So, the problem is actually simple: the DataContext of your MyClass instance is inherited from the window, that is, the window itself ( Window there or MainWindow ). But at the window, your DependencyProperty not there, they are in MyClass ! And Binding goes to the window - a mess.

Then, in your piece of code, the DependencyProperty MyProperty , and the Binding goes to MyProp1 - you need to fix it, but it will not take off again.

And also in the declaration of DependencyProperty MyProp2 error - instead of typeof(MainWindow) , of course, typeof(MyClass) necessary. Here it is.

Oh, and more! Your MyClass instance is in the resources, that is, it is not part of the visual tree. So it is impossible, nothing will work. Put it in the window. (If you need to temporarily hide, set the attribute Visibility="Collapsed" .)