简体   繁体   中英

Set TabItem DataContext Inidividiually?

I have a TabControl with some items in it based on a class. 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.

I currently have.

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#

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".

What can I do to fix this problem?

The problem probably lies inside 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.

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.

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