wpf 将用户控件 属性 绑定到 mainwondow 的数据上下文

wpf bind usercontrol property to datacontext of mainwondow

我有一个用户控件(一个标签和一个文本框。我想将用户控件的文本绑定到来自 DTO class 员工的 属性 名称(Employee.Name ) 其中绑定设置在主 window 中,在用户控件之外。这是我的用户控件(查看控件标签和文本

<UserControl x:Class="TestCompany.controls.textEdit"
         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" 
         xmlns:local="clr-namespace:TestCompany.controls"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300">

<Grid >
    <Grid.RowDefinitions>
        <RowDefinition Height="60" />
        <RowDefinition MinHeight="50" />
    </Grid.RowDefinitions>
    <Label Name="label" Content="{Binding Caption}" Grid.Row="0" FontSize="35" FontWeight="Light"/>
    <TextBox Name="textbox" Text="{Binding Text}" Grid.Row="1" FontSize="33" Background="White"  />
</Grid>

Caption是控件的标题,Text显示值

这是背后的代码

public string Caption
    {
        get
        {
            return (string)GetValue(CaptionProperty);
        }

        set
        {
            SetValue(CaptionProperty, value);                
        }
    }

    public static DependencyProperty CaptionProperty =
        DependencyProperty.Register("Caption", typeof(string), typeof(textEdit), null);


    public string Text
    {
        get
        {
            return (string)GetValue(TextProperty);                
        }

        set
        {
            SetValue(TextProperty, value);                
        }
    }

    public static DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(textEdit), null);

现在主要 window,这就是我使用自定义控件的方式

<controls:textEdit Caption="Name" Text="{Binding Name}" Grid.Column="0" HorizontalAlignment="Stretch" Margin="0,0,20,0" />

然后在 mainwindow 中,从 Employees 列表中,我选择了一个并将其分配给 context

this.DataContext = EmployeeObject; // Name = "Joe"

但是用户控件的Text属性不显示"Joe"。甚至 属性 的 setter 也不会被调用。奇怪的是,如果在我的用户控件的构造函数中,我没有将 UserControl.Datacontext 分配给 this

DataContext = this; // within the constructor of UserControl

然后连Label控件都是空的(label控件链接到Caption依赖项属性)。我在 Whosebug 和其他地方看过无数类似的问题。 (RelativeSource Self 等...)。没有任何作用...我的用户控件的文本 属性 不显示主 window...

中设置的 Datacontext 的值

如有任何帮助,我们将不胜感激

您需要将 UserControlDataContext 设置为主 window 的 DataContext,并将 GridDataContext 设置为 UserControl。这意味着当 UserControl 寻找它的数据时,它会在它从 MainWindow 继承的 DataContext 中查找,但是当你的 Grid 寻找它的数据时,它会在 [=12] 中寻找=].你这样做:

<UserControl ... 
     d:DesignHeight="300" d:DesignWidth="300"
     x:Name="ThisControl">

<Grid DataContext="{Binding ElementName=ThisControl}">
...

参见 http://blog.scottlogic.com/2012/02/06/a-simple-pattern-for-creating-re-useable-usercontrols-in-wpf-silverlight.html