【问题标题】:wpf binding to element from another xaml filewpf 绑定到另一个 xaml 文件中的元素
【发布时间】:2016-10-14 01:36:44
【问题描述】:

我正在尝试将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>

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的声明有问题还是绑定有问题?

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

【问题讨论】:

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

标签: c# wpf xaml view binding


【解决方案1】:

假设您想要的只是能够将string 绑定到Tab1“文本”,请在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"));

然后在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>

然后在您的 Window XAML 中:

<local:Tab1 TabText="The text you want to place."/>

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

<local:Tab1 TabText="{Binding SomeProperty}"/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    相关资源
    最近更新 更多