将usercontrol的datacontext绑定到mainwindow

时间:2015-06-23 18:21:49

标签: wpf xaml user-controls

我有一个位于MainWindow内部的UserControl。 UserControl运行查询并在其中填充某些TextBlock。我还想从相同的返回数据填充MainWindow中的TextBlock。

如何将MainWindow数据绑定到UserControl?我试过这个:

<MainWindow DataContext="{Binding Path=DataContext, ElementName=UserControlName}">

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

这是一个简单的工作示例。

UserControl XAML只包含一个双向绑定文本框。相关的源代码比你需要的更冗长,你可以设置一个数据上下文,但它只是为了清楚属性的来源:

<TextBox x:Name="ucTextBox" 
         Text="{Binding Path=UcText, 
                        RelativeSource={RelativeSource AncestorType={x:Type local:UserControl1}}, 
                        Mode=TwoWay, 
                        UpdateSourceTrigger=PropertyChanged}" />

后面的用户控制代码声明依赖属性,或者如此处所示,实现INotifyPropertyChanged的常规属性:

private string _ucText;
public string UcText
{
    get { return _ucText; }
    set
    {
        _ucText = value;
        OnPropertyChanged("UcText");
    }
}

然后,MainWindow XAML将其自己的文本块设置为用户控件中文本框的text属性,如下所示:

<StackPanel Orientation="Vertical">
    <TextBlock Text="{Binding Path=UcText, ElementName=uc1}"/>
    <local:UserControl1 x:Name="uc1" />
</StackPanel>

MainWindow代码隐藏不需要额外的内容。

这导致的是一个文本框(在用户控件中),当您在其中键入时,它会更新主窗口上的文本块。

相关问题