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]}" />
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
FrameworkElementto setValue, thats the actual dependecy property object, you’re passing the datacontext object twice. In other words the call should bei 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
GlobalContexta 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