dbomb7
dbomb7

Reputation: 51

Bind to DependencyProperty on Custom Class

I'm having issues binding to a custom class. The dependencyproperty does not seem to get 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>

"Test" in my ViewModel is a property that I can bind a Label to with no issues. Am I doing something wrong here in this implementation?

Update: This works if I inherit from Freezable instead of DependencyObject. I'm not quite sure why, hopefully somone can explain this.

Upvotes: 5

Views: 2204

Answers (3)

Andreas M.
Andreas M.

Reputation: 192

Since content seems to be of type object -which leads me to believe that will be used to host a class- , the problem might actually be the depth of "listening". If a property of Test changes (a.k.a. change of a string) you will be notified. If a property of Test is an object that doesn't inherit from DependencyObject and a property of it gets changed, you will not get notified. The last scenario goes on recursively.

According to Microsoft Documentation :

[...]

Detailed change notification: Unlike other DependencyObject objects, a Freezable object provides change notifications when sub-property values change.

[...]

Upvotes: 0

Xcalibur37
Xcalibur37

Reputation: 2323

You can also use the FrameworkElement.SetBinding method on the Dependency Property in your code behind. Then you don't need to set the data context for the entire page (since DataContext and DP's don't mix well).

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

Sample:

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

Upvotes: 0

brunnerh
brunnerh

Reputation: 184441

There is no context in the Resources, the DataResource would need to be placed somewhere in the UserControl so it can inherit the DataContext so that the binding (which is relative to the DataContext unless a source is defined) is complete.

(A problem with that is that DependencyObject don't even have a "real" DataContext as that property belongs to FrameworkElement, if you are lucky there is an artificial context though)

Upvotes: 3

Related Questions