I am trying to bind some data from the MainWindow
to a second file (Type: UserControl
). The second xaml-file should contain the data from a TabItem
. I found this answer: wpf : Bind to a control in another xaml file but somehow I am not getting it, maybe because I am new to wpf and xaml.
I made a short example, to show my problem:
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>
Tab1 (Content for 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>
I wonder if the declaration of the DataContext
is wrong or if the binding is the problem?
I really appreciate any help you can provide.
Assuming all you would want is to be able to bind a string
to the Tab1
"text", create a DependencyProperty
in the code-behind for the 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"));
Then in the 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>
Then in your Window XAML:
<local:Tab1 TabText="The text you want to place."/>
Or you can also bind to TabText, eg:
<local:Tab1 TabText="{Binding SomeProperty}"/>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.