tabControl中有多个userControl实例 [英] multiple userControl instances in tabControl

查看:234
本文介绍了tabControl中有多个userControl实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个tabControl绑定到一个可观察的集合。
在headerTemplate中,我想绑定到一个字符串属性,在contentTemplate中,我放置了一个用户控件。

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.

这是MainWindow.xaml:

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>

及其后面的代码:

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;
    }
}

因此,这种情况下的问题(已指定itemTemplate以及controlTemplate)是,我只为用户控件获得一个一个实例,在该实例中,我想为绑定到的每个项目都拥有一个实例。

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.

推荐答案

尝试一下:

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

这篇关于tabControl中有多个userControl实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆