简体   繁体   English

单独设置TabItem DataContext吗?

[英]Set TabItem DataContext Inidividiually?

I have a TabControl with some items in it based on a class. 我有一个基于类的其中某些项目的TabControl。 I'd like to bind that class to the TabItem itself so that I can have a mix of user controlled and class controlled TabItems. 我想将该类绑定到TabItem本身,以便可以混合使用用户控制和类控制的TabItem。

I currently have. 我目前有。

XAML XAML

<Window.Resources>
    <TextBlock x:Key="TabItem_Prefab" Text="{Binding Name}"/>
</Window.Resources>

<TabControl>
    <TabItem Header="A" Name="TabControl_A">
        <StaticResource ResourceKey="TabItem_Prefab"/>
    </TabItem>
    <TabItem Header="B" Name="TabControl_B">
        <StaticResource ResourceKey="TabItem_Prefab"/>
    </TabItem>
    <TabItem Header="Options">
        <TextBlock Text="Stuff"/>
    </TabItem>
</TabControl>

C# C#

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModelTest a = new ViewModelTest() { Name = "string" };
        ViewModelTest b = new ViewModelTest() { Name = "Cheese" };
        TabControl_A.DataContext = a;
        TabControl_B.DataContext = b;
    }
}

public class ViewModelTest
{
    public string Name { get; set; }
}

The problem with this is that the tab for TabControl_A shows "cheese" when it should be bound to the one that says "string". 这样做的问题是,当TabControl_A的选项卡应该绑定到说“ string”的选项卡时,它会显示“ cheese”。

What can I do to fix this problem? 我该怎么做才能解决此问题?

The problem probably lies inside StaticResource TabItem_Prefab. 问题可能出在StaticResource TabItem_Prefab中。 It seems to me that the usual Binding works 在我看来,通常的绑定有效

   <TabControl>
            <TabItem Header="A" Name="TabControl_A">
                <TextBlock Text="{Binding Name}"/>
            </TabItem>
            <TabItem Header="B" Name="TabControl_B">
                <TextBlock Text="{Binding Name}"/>
            </TabItem>
            <TabItem Header="Options">
                <TextBlock Text="Stuff"/>
            </TabItem>
    </TabControl>

Show your StaticResource. 显示您的StaticResource。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM