WPF绑定到另一个XAML文件中的元素

5
我希望你可以将MainWindow中的一些数据绑定到第二个文件(类型:UserControl)中。第二个xaml文件应该包含来自TabItem的数据。 我找到了这个答案:wpf : Bind to a control in another xaml file, 但是由于我是wpf和xaml的新手,所以某种程度上我无法理解它。
我做了一个简短的例子来说明我的问题:
MainWindow:
<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>

选项卡1(Tab1)(选项卡项目内容):

<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。 - lentinant
1个回答

4
假设您想要的只是能够将字符串绑定到"Tab1"的 "text",请在代码后台为 "UserControl" 创建一个 "DependencyProperty":
假設您希望的只是能夠將字串綁定到 "Tab1" 的 "text",請在程式碼背景中為 "UserControl" 建立一個 "DependencyProperty":
public string TabText
{
    get { return (string)GetValue(TabTextProperty); }
    set { SetValue(TabTextProperty, value); }
}
public static readonly DependencyProperty TabTextProperty = DependencyProperty.Register("TabText", typeof(string), typeof(Tab1), new PropertyMetadata("Default"));

那么在 Tab1 的 XAML 中:

<UserControl x:Class="BindingBetweenFiles.Tab1"
     ...
     xmlns:local="clr-namespace:BindingBetweenFiles"
     mc:Ignorable="d" 
     DataContext="local:MainWindow"
     d:DesignHeight="300" d:DesignWidth="300"
     x:Name="tab1Control">
<Grid>
    <Label Content="{Binding ElementName=tab1Control, Path=TabText"/>
</Grid>

然后在您的窗口XAML中:
<local:Tab1 TabText="The text you want to place."/>

或者你也可以绑定到TabText,例如:
<local:Tab1 TabText="{Binding SomeProperty}"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接