【发布时间】:2016-10-14 01:36:44
【问题描述】:
我正在尝试将MainWindow 中的一些数据绑定到第二个文件(类型:UserControl)。第二个 xaml 文件应包含来自 TabItem 的数据。
我找到了这个答案:wpf : Bind to a control in another xaml file
但不知何故我没有得到它,也许是因为我是 wpf 和 xaml 的新手。
我做了一个简短的例子来说明我的问题:
主窗口:
<Window x:Class="BindingBetweenFiles.MainWindow"
...
xmlns:local="clr-namespace:BindingBetweenFiles"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TabControl Height="200">
<TabItem Header="Tab 1">
<local:Tab1 />
</TabItem>
</TabControl>
<TextBlock Name="txtblock1">This text should be shown in the tab.</TextBlock>
</StackPanel>
</Window>
Tab1(TabItem 的内容):
<UserControl x:Class="BindingBetweenFiles.Tab1"
...
xmlns:local="clr-namespace:BindingBetweenFiles"
mc:Ignorable="d"
DataContext="local:MainWindow"
d:DesignHeight="300" d:DesignWidth="300">
<Grid>
<Label Content="{Binding DataContext.txtblock1.Text, RelativeSource={
RelativeSource AncestorType={x:Type local:MainWindow}}}"/>
</Grid>
不知道是DataContext的声明有问题还是绑定有问题?
非常感谢您提供的任何帮助。
【问题讨论】:
-
使用MVVM模式不是更好吗?仅将 xaml 文件作为表示形式,并将所有实际数据存储在单独的 ViewModel 类中。然后,您的 MainWindow 和 UserControl 都可以绑定到 ViewModel 的相同属性,将其用作 DataContext。