wpf 绑定到另一个 xaml 文件中的元素

use*_*232 5 c# wpf xaml binding view

我正在尝试将一些数据从 绑定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>
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

我想知道是声明DataContext错误还是绑定有问题?

我非常感谢您提供的任何帮助。

小智 4

假设您想要的只是能够将 a 绑定stringTab1“文本”,请DependencyProperty在代码隐藏中创建 a UserControl

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"));
Run Code Online (Sandbox Code Playgroud)

然后在Tab1XAML 中:

<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>
Run Code Online (Sandbox Code Playgroud)

然后在您的 Window XAML 中:

<local:Tab1 TabText="The text you want to place."/>
Run Code Online (Sandbox Code Playgroud)

或者你也可以绑定到TabText,例如:

<local:Tab1 TabText="{Binding SomeProperty}"/>
Run Code Online (Sandbox Code Playgroud)