Multiple instances of userControl in tabControl

I have a tabControl associated with an observable collection. In the headerTemplate, I would like to bind to a string property, and in the contentTemplate I placed a user control.

Here is the code for MainWindow.xaml:

<Grid>
    <Grid.Resources>            
        <DataTemplate x:Key="contentTemplate">
                <local:UserControl1 />
        </DataTemplate>

        <DataTemplate x:Key="itemTemplate">
                <Label Content="{Binding Path=Name}" />
        </DataTemplate>
    </Grid.Resources>

    <TabControl IsSynchronizedWithCurrentItem="True" 
                ItemsSource="{Binding Path=Pages}"
                ItemTemplate="{StaticResource itemTemplate}"
                ContentTemplate="{StaticResource contentTemplate}"/>

</Grid>

And his code is behind:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        this.DataContext = new MainWindowViewModel();
    }        
}

public class MainWindowViewModel
{
    public ObservableCollection<PageViewModel> Pages { get; set; }

    public MainWindowViewModel()
    {
        this.Pages = new ObservableCollection<PageViewModel>();
        this.Pages.Add(new PageViewModel("first"));
        this.Pages.Add(new PageViewModel("second"));
    }
}

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

    public PageViewModel(string name)
    {
        this.Name = name;
    }
}

So the problem in this scenario (by specifying itemTemplate as well as controlTemplate) is that I get an instance of one for the user control, where I want to have an instance for each element that is required.

+3
source share
3 answers

Try the following:

<TabControl IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Pages}">
    <TabControl.Resources>
        <DataTemplate x:Key="contentTemplate" x:Shared="False">
            <local:UserControl1/>
        </DataTemplate>
        <Style TargetType="{x:Type TabItem}">
            <Setter Property="Header" Value="{Binding Name}"/>
            <Setter Property="ContentTemplate" Value="{StaticResource contentTemplate}"/>
        </Style>
    </TabControl.Resources>
</TabControl>
+2
source

: Shared = "False"

false, Windows Presentation Foundation (WPF), , .

+1

Equals() PageViewModel.

public override bool Equals(object obj)
{
    if (!(obj is PageViewModel)) return false;

    return (obj as PageViewModel).Name == this.Name;
}

- .

Name. ID.

-1

Source: https://habr.com/ru/post/1704061/


All Articles