This question is not "how to do it", but I want to understand "why this is happening."
There is a window, in it a DataGrid, in a DataGrid there is a DataGridTemplateColumn, in which DataTemplate with UserControl
Inside the target UserControl, both the DataContext of the item and the parent DataContext of the window are required for binding to the commands.
We try the option with an explicit transfer, so as not to bathe with AncestorLevel
To remove UserControl's dependency on the nesting level, we make it a DependencyProperty
public static readonly DependencyProperty MainContextProperty = DependencyProperty.Register( "MainContext", typeof(object), typeof(CellView), new PropertyMetadata(default(object))); public object MainContext { get { return (object) GetValue(MainContextProperty); } set { SetValue(MainContextProperty, value); } }
Passing the parent context .:
<CellView MainContext="{Binding DataContext, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl, Mode=OneTime}}" />
Context inside UserControl, we are going to command:
Command="{Binding MainContext.MyCommand, RelativeSource={RelativeSource AncestorType=UserControl, Mode=FindAncestor, AncestorLevel=1}, Mode=OneTime}"
And it does not work. It works if you put OneWay. And if you make AncestorLevel = 2, then it will get to the parent context and will work with OneTime
What happens to the DataContext during this transfer? And why does Oneway work?