c#-在“ MainView”中设置DataContext会过滤掉所有“ ChildView的”

提问

我想知道这是否是.NET的标准功能:在ParentView中设置DataContext时,它会向下过滤所有子视图.

假设您有ParentView,ChildView1和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>

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;
        }

注意:设置第一个DataContext时的断点

当我只设置了ParentView的DataContext时,为什么要设置所有DataContext?

我该怎么做才能防止这种情况发生?

最佳答案

这是标准行为,通常是期望的.为防止这种情况,请在标记中将DataContext设置为{x:Null}
评论