I would like to know if this is a standard feature of .NET: when setting the DataContext in the ParentView, it filters down to all child views.
Say you have ParentView, ChildView1 and ChildView2:
<UserControl x:Class="DXWPFApplication1.ParentView"
xmlns:view="clr-namespace:DXWPFApplication1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<view:ChildView1 x:Name="childView1"/>
</Grid>
</UserControl>
<UserControl x:Class="DXWPFApplication1.ChildView1"
xmlns:view="clr-namespace:DXWPFApplication1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<view:ChildView2 x:Name="childView2"/>
</Grid>
</UserControl>
Code behind of ParentView:
public ParentView()
{
InitializeComponent();
DataContext = "ViewModel"; //BreakPoint here
//
//When the first DataContext is set, all the DataContext's below are set as well
//
childView1.DataContext = DataContext;
childView1.childView2.DataContext = DataContext;
}
NOTE: Breakpoint when setting first DataContext
Why are all the DataContexts set when I have only set the ParentView’s DataContext?
What can I do to prevent this from happening?
This is standard behaviour, and normally desired. To prevent it, set DataContext to {x:Null} in your markup