multiple userControl instances in tabControl

2019-01-25 22:04发布

问题:

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

Here's the code for the 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 its code 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 (having specified an itemTemplate as well as a controlTemplate) is that I only get one instance for the user-control, where I want to have an instance for each item that is bound to.

回答1:

Try this:

<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:

Try setting

x:Shared="False"

When set to false, modifies Windows Presentation Foundation (WPF) resource retrieval behavior such that requests for a resource will create a new instance for each request, rather than sharing the same instance for all requests.



回答3:

You need to override the Equals() Method of your PageViewModel class.

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

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

Something like this should work.

Now it is looking for the same property of the value Name. Otherwise you could also add a ID Property which is unique.