Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting the DataContext in "MainView" filters down to all "ChildView's"

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?

like image 662
Willem Avatar asked Jan 28 '26 12:01

Willem


2 Answers

This is standard behaviour, and normally desired. To prevent it, set DataContext to {x:Null} in your markup

like image 153
James L Avatar answered Jan 31 '26 00:01

James L


A component in the visual tree inherts the data context from its parent. Your child view resides in the visual tree of the parent view so it will get the parent context assigned. You need to explicitly set it to something different if you want to change it (either inside the child view constructor or in the xaml, for example <view:ChildView2 DataContext="{x:Null}" x:Name="childView2"/>).

Why was that done: Because it is almost always what you want.

like image 22
ChrisWue Avatar answered Jan 31 '26 00:01

ChrisWue



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!