c# – WPF将内部控件与父数据上下文绑定

我做了一个用户控件

<UserControl x:Class="MyApp.MyControl"
         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"  x:Name="uc">
<Grid Width="Auto" Height="Auto">
    <TextBlock Text="{Binding Path=DataContext.TextContent, ElementName=uc}"/>
    <TextBlock Text="{Binding Path=DataContext.TextContent2, ElementName=uc}"/>
</Grid>

我希望定义的控件(uc)中的子控件将绑定到uc.DataContext的属性.我使用定义的控件如下:

<Window x:Class="Tms.TMSClient.Views.MainWindow" Name="window"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:control="clr-namespace:MyApp"
    xmlns:ribbon="clr-namespace:Microsoft.Windows.Controls.Ribbon;assembly=RibbonControlsLibrary">      

    <control:MyControl DataContext="{Binding Path=MyControlVM}"/>

分配给窗口的DataContext具有以下结构:WindowVM.MyControlVM.TextContent.

给定的代码不起作用,因为文本框的DataContext被绑定到WindowVM.我认为问题可能是因为内部文本框在定义的控件(uc)之前被绑定,因此uc的有界DataContext尚未生效.

我想要的是:自定义控件(MyControl)将绑定到其对应的viewmodel(MyControlVM),MyControl的内部元素将绑定到MyControlVM的属性.

你对这个问题有什么解决方案吗?

最佳答案
<TextBlock Text="{Binding Path=TextContent}"/>

在我的测试应用程序中为我工作.

MainWindow.xaml

<Window x:Class="DataContextTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:my="clr-namespace:DataContextTest"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <my:MyOuterDataContext />
</Window.DataContext>
<Grid>
    <my:MyControl DataContext="{Binding Path=MyInnerDataContext}" />
</Grid>

MyControl.xaml

<UserControl x:Class="DataContextTest.MyControl"
         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>
    <TextBlock Text="{Binding Path=TextContent}" />
</Grid>

DataContexts:

public class MyOuterDataContext
{
    public MyInnerDataContext MyInnerDataContext { get; set; }

    public MyOuterDataContext()
    {
        MyInnerDataContext = new MyInnerDataContext();
    }
}

public class MyInnerDataContext
{
    public string TextContent { get { return "foo"; } }
}

转载注明原文:c# – WPF将内部控件与父数据上下文绑定 - 代码日志