How do you bind data from the view model into an object in the resources of the user control? Here is a very abstract example:
<UserControl ...
xmlns:local="clr-namespace:My.Local.Namespace"
Name="userControl">
<UserControl.Resources>
<local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ???}" />
</UserControl.Resources>
<Grid>
<local:GroupingConsumer Name="groupingConsumer1" Provider={StaticResource groupingProvider"} />
<local:GroupingConsumer Name="groupingConsumer2" Provider={StaticResource groupingProvider"} />
</Grid>
</UserControl>
How do I bind GroupValue
to a property in the view model behind this view. I've tried the following:
<local:GroupingProvider x:Key="groupingProvider" GroupValue="{Binding ElementName=userControl, Path=DataContext.Property}"/>
But this doesn't work.
Edit:
GroupProvider
extends DependencyObject
and GroupValue
is the name of a DependencyProperty
. I'm getting the following error:
System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=DataContext.Property; DataItem=null; target element is 'GroupingProvider' (HashCode=47478197); target property is 'GroupValue' (type 'TimeSpan')
This seems to suggest that it cannot find userControl
.
More Edit:
Nobody has an answer to my question? Is there not a way to do this?
I know its a bit late, but i had the same problem. Ricks answer is right, you need to inherit from
Freezable
.The following Code gave me the same error as you got
Not working resource:
Xaml:
My viewmodel is bound to the
DataContext
of theUserControl
.Error:
Working resource class:
Unfortunately i dont know why it have to be a
Freezable
.In order to enable binding,
GroupingProvider
needs to be derived fromFreezable
orFrameworkElement
orFrameworkContentElement
andGroupValue
needs to be aDependencyProperty
.