[英]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.