Failed to bind to DataContext
I have a very strange problem. I am trying to bind a property to the DataContext but it doesn't work. This is what I am doing (under Window.Resources):
<myNS:MyClass x:Key="myObj" MyProp="{Binding}"/>
Elsewhere in the code, I set the data context like this:
myWindow.DataContext = MyNameSpace.MySingleton.Instance;
I didn't get any errors, but the binding didn't happen. So I added a Debug converter to see if I can figure out what's going on:
<myNS:MyClass x:Key="myObj" MyProp="{Binding Converter={StaticResource Debug}}"/>
I set a breakpoint in the converter and the passed value was null. Thinking that everything was out of order, I set a breakpoint on the line that sets the DataContext. It was hit first, then a breakpoint in the converter. Therefore the DataContext is set before the binding takes place.
Finally, to try and get something to work, I changed this:
<myNS:MyClass x:Key="myObj" MyProp="{Binding Source={x:Static myNS:MySingleton.Instance}}"/>
It worked.
I really don't like to distribute such bindings. I would rather just bind to the DataContext. The window in question contains many property bindings in the DataContext and they all work fine.
Can someone explain what I am doing wrong here?
JAB
source to share
What an idiot I am!
I started answering @BradleyDotNET (thanks for the answer, btw it helped me solve the problem) and figured out the solution. My DOES class is derived from FrameworkElement. I did this because I needed to use data binding even though it has no visible component.
I posted another question related to how to create an object declared in the resources section . I would still like to know the answer to this question, but since my class comes from FrameworkElement, I don't need to declare it in the resources section; I can put it right in the tree. This causes it to be created and inherits from DataContext.
source to share
Resources, as well as some other elements such as context menus, are not part of the visual tree.
Thus, they do not have a FrameworkElement control to get the data context. Typically a standard class will not use the binding syntax as it requires getting from DependencyObject
, but if you need to bind to a resource (say a converter), you can use this trick:
- Give your root element
x:Name="Root"
-
Use your bindings like this:
MyProp="{Binding Source={x:Reference Root}, Path=DataContext.<YourProp>
This binds using the root element of the struct as a "starting point" and you can get to the data context normally.
source to share