Bind to DependencyProperty in a custom class

I'm having trouble binding to a custom class. It looks like the dependency property is not getting the correct value from my viewmodel. Here is my custom class:

public class DataResource : DependencyObject { public static readonly DependencyProperty ContentProperty = DependencyProperty.Register("Content", typeof(object), typeof(DataResource)); public object Content { get { return (object)GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } } 

And in my UserControl resources I have:

  <UserControl.Resources> <local:DataResource x:Key="dataResource" Content="{Binding Test}"></data:DataResource> </UserControl.Resources> 

The "test" in my ViewModel is a property with which I can bind a shortcut without any problems. Am I doing something wrong here in this implementation?

Update. This works if I inherit from Freezable and not DependencyObject. I'm not quite sure why, I hope someone can explain this.

+4
source share
2 answers

There is no context in Resources , the DataResource needs to be placed somewhere in the UserControl so that it can inherit the DataContext , so that the binding (which is relative to the DataContext , if only the source is defined) is completed.

(The problem is that DependencyObject doesn’t even have a β€œreal” DataContext , since this property belongs to FrameworkElement , if you are lucky there is an artificial context)

+3
source

You can also use the FrameworkElement.SetBinding method for the Dependency property in your code. Then you do not need to set the data context for the entire page (since the DataContext and DP do not mix well).

Here is the MSDN: http://msdn.microsoft.com/en-us/library/ms598273.aspx

Example:

 MyData myDataObject = new MyData(DateTime.Now); Binding myBinding = new Binding("MyDataProperty"); myBinding.Source = myDataObject; myText.SetBinding(TextBlock.TextProperty, myBinding); 
0
source

Source: https://habr.com/ru/post/1386176/


All Articles