Setting the DataContext to "MainView" filters up to all "ChildView",

I would like to know if this is a standard feature of .NET: when configured DataContextin, ParentViewit filters everything child views.

Suppose 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 ParentView:

public ParentView() 
        {
            InitializeComponent();

            DataContext = "ViewModel"; //BreakPoint here

            //
            //When the first DataContext is set, all the DataContext below are set as well
            //

            childView1.DataContext = DataContext;
            childView1.childView2.DataContext = DataContext;
        }

NOTE. Breakpoint when setting firstDataContext

Why are all DataContexts installed when I just installed ParentView DataContext?

What can I do to prevent this from happening?

+3
source share
3 answers

This is standard behavior and is usually desirable. To prevent it, set the DataContext to {x: Null} in your markup

+2
source

. , . - , ( , xaml, <view:ChildView2 DataContext="{x:Null}" x:Name="childView2"/>).

: , .

+1

, ViewModels , , ViewModels.

, MainViewModel , ChildViewModel1 ChildViewModel2. usercontrols

DataContext="{Binding ChildViewModel1}"

DataContext="{Binding ChildViewModel2}"

DataContext MainViewModel

+1

All Articles