Reputation: 4751
I am trying to set datacontext of a control using the following code:
public object GlobalContext
{
set { this.SetValue(global.DataContext as DependencyProperty , value); }
}
Where global is a control, in this case a stackpanel.
When I mouse over global.DataContext
it says its a dependency property so I figured it should work, but I get the following error:
A 'Binding' cannot be set on the 'GlobalContext' property of type 'ResourceModuleAccessView'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject.
Any way I can make this work?
Edit 1: In the user control I have:
<StackPanel x:Name="global" Orientation="Horizontal">
and in the places where I am trying to reuse the control:
<my:ResourceModuleAccessView
ControlName="Usage Monitoring"
GlobalContext="{Binding Path=moduleAccess.GlobalAccess[ResourceModule.UsageMonitoring]}"
GroupContext="{Binding Path=moduleAccess.Items[ResourceModule.UsageMonitoring]}" />
Upvotes: 0
Views: 1247
Reputation: 6275
Your GlobalContext class must inheirit from DependencyObject if you are going to use it as a binding target or use the SetValue method. Also, you should pass the static DataContext*Property* from FrameworkElement
to setValue, thats the actual dependecy property object, you're passing the datacontext object twice. In other words the call should be
SetValue(FrameworkElement.DataContextProperty,value);
i suspect there is something else wrong than this code though, can you post your xaml?
-edit-
Thanks for adding the code, since you're binding To your class (you class is a binding target as opposed to a binding source), you must make it a DependecyObject and make your GlobalContext
a DependecyProperty.
Also note that when the binding system sets a dependecy property, it doesnt use the regular clr property, it uses the DependencyProperty object directly. This means that if you want to register a call back for when the property is changed, you must do that in the call to Register when you create the DependecyProperty
Upvotes: 2
Reputation: 70160
The DataContext property, which is defined on FrameworkElement
is a dependency property, i.e. it is a property that is 'backed' by the WPF dependency property framework. However the type of this property is object
. The fact that it is a dependency property tells you how it is stored, not the type of the data stored within it.
Upvotes: 0