[英]wpf binding to element from another xaml file
我试图将MainWindow
中的一些数据绑定到第二个文件(Type: UserControl
)。 第二个xaml文件应包含TabItem
的数据。 我找到了这个答案: wpf:绑定到另一个xaml文件中的控件但不知何故我没有得到它,也许是因为我是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
的声明是错误的还是绑定是问题?
我非常感谢您提供的任何帮助。
假设你想要的就是能够将string
绑定到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>
然后在你的Window XAML中:
<local:Tab1 TabText="The text you want to place."/>
或者您也可以绑定到TabText,例如:
<local:Tab1 TabText="{Binding SomeProperty}"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.