2016-06-13 107 views
3

我试图将一些数据从MainWindow绑定到第二个文件(类型:UserControl)。第二个xaml文件应该包含来自TabItem的数据。 我发现这个答案:wpf : Bind to a control in another xaml file 但不知何故,我没有得到它,也许是因为我是新来的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的声明是错误的,或者如果绑定是问题?

我真的很感谢您能提供任何帮助。

+0

是不是更好地使用MVVM模式?仅将xaml文件用作表示形式,并将所有实际数据存储在单独的ViewModel类中。然后,您的MainWindow和UserControl都可以绑定到ViewModel的相同属性,并将其作为DataContext使用。 – lentinant

回答

0

假设所有你想要的是能够结合stringTab1“文本”,为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}"/> 
+0

谢谢,它的工作原理。 – user6460232