In my application, I have a data structure, and certain controls need to be bound to some of the properties in that structure, for example:
<StackPanel>
<Label Content="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Lcg.DisplayTitle}" ToolTip="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Lcg.Description}"/>
<Label Content="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Tcg.DisplayTitle}" ToolTip="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Tcg.Description}"/>
<Label Content="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Vcg.DisplayTitle}" ToolTip="{Binding Path=ConditionInputDataTemplate.Vessel.Loading.Vcg.Description}"/>
</StackPanel>
This results in very long markups, so I solved this by narrowing down the scope of the parent control DataContext
, like this:
<StackPanel DataContext="{Binding Path=ConditionInputDataTemplate.Vessel.Loading}">
<Label Content="{Binding Path=Lcg.DisplayTitle}" ToolTip="{Binding Path=Lcg.Description}"/>
<Label Content="{Binding Path=Tcg.DisplayTitle}" ToolTip="{Binding Path=Tcg.Description}"/>
<Label Content="{Binding Path=Vcg.DisplayTitle}" ToolTip="{Binding Path=Vcg.Description}"/>
</StackPanel>
However, I now need to introduce a new element inside the same StackPanel
that is bound to a property a few steps “above” the parent DataContext
, so I’d like to specify full path for that property while keeping others the same, like this:
<StackPanel DataContext="{Binding Path=ConditionInputDataTemplate.Vessel.Loading}">
<Label Content="{Binding Path=Lcg.DisplayTitle}" ToolTip="{Binding Path=Lcg.Description}"/>
<Label Content="{Binding Path=Tcg.DisplayTitle}" ToolTip="{Binding Path=Tcg.Description}"/>
<Label Content="{Binding Path=Vcg.DisplayTitle}" ToolTip="{Binding Path=Vcg.Description}"/>
<CheckBox Content="{Binding Path=ConditionInputDataTemplate.Vessel.Options.TreatMassPropertiesAsIndependent}"/>
</StackPanel>
This, of course, fails, because CheckBox
is searching for it’s assigned property using the DataContext
of it’s parent Stackpanel
, rather than using the DataContext
of the Page
. Is there any way that I can make that CheckBox
ignore the DataContext
of the StackPanel
, so I can specify the full path to the target property?
I attempted setting DataContext
for that CheckBox explicitly (CheckBox DataContext="{Binding Path=ConditionInputDataTemplate}"
, but it still starts searching for it from the StackPanel
‘s DataContext
. I can’t find a way to make CheckBox
‘s DataContext
escape the influence of StackPanel
.
P.S. I realize this code example seems like a bad design, and it appears simpler to just move the CheckBox
outside the StackPanel
, but this is heavily simplified code snippet, and there are good reasons for this kind of architecture in the real application.