I have a workable solution but I’m pretty convinced there’s a better way of writing this.
I have a User Control with a Data Grid inside. The Data Grid’s ItemsSource is set to {Binding Path=MyView} where MyView is an ICollectionView property of the View Model. The User Control’s data context is set to the View Model.
In the data grid, I have a check box header. I want to bind the IsChecked state of the checkbox to a property in the View Model.
This is what I have so far and it seems to work, but I’m concerned this binding is unnecessarily complex. The UI is pretty basic so I would expect the binding to be more straightforward to write than it was.
Is there a better way to express such a binding?
<DataGridTemplateColumn.HeaderTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Views:MyUserControlClass}}, Path=DataContext.AllRowsSelected}" />
</DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>
In such situations I use
instead of
Also you can use
In this case I assume that LayoutRoot is the name of the element who’s parent is the user control.
Parentis its property. So binding is set to parent’s DataContext property.I prefer the last variant, because providing name for user control limits its usage.
EDIT
About LayoutRoot. This name is often provided for the top element in a Window or a UserControl, or just some layout:
There’s nothing special about this name. Just often used. Same situation as with namespace aliases in xaml: sys (points to mscorlib), local (points to your application namespace), etc.