DataBinding to their own class

The question was asked: 6 years 11 months ago   views: 23
0

Hello, faced such 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 properties propdp

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 doesn't the data binding?

Asked: angry angry 21-06-2012 в 19:35:07
Why the second owner property type is typeof(MainWindow)? - andreycha andreycha 29-06-2012 в 11:01:15

Answers   1

0

Doing archaeology :)

So the problem is really simple: DataContext from your instance of MyClass is inherited from the window that is the window itself (Window there or MainWindow). But at the window of your DependencyProperty nope, they're in MyClass! A Binding goes to the window -- the disorder.

Then, in your piece of code declared as a DependencyProperty MyProperty, and the Binding goes to the MyProp1 -- need to fix, but then again not fly.

And in the Declaration of DependencyProperty MyProp2 error -- instead of typeof(MainWindow) must, of course, typeof(MyClass). Here.

Oh, but still! Your instance of MyClass lies in resources that is not part of visual tree. Wrong, nothing would work. Put it in the window. (If you need to temporarily hide the select the attribute Visibility="Collapsed".)

Answered: VladD VladD 23-11-2012 в 16:18:11