WPF TabControl Templating

老子叫甜甜 提交于 2020-01-05 04:37:26

问题


I am a new WPF user and I am trying to wrap my head around templating. In particular I am trying to template a TabControl.

I am confused by the controls that actually get generated when the TabControl is bound to data. What I need is for each tab to have a separate copy of the controls in it's content section. What I have found is that it appears that a single set of controls are created, and when the user clicks from tab to tab, just the bound data changes.

Project Description:

The example project consists of a single view with a TabControl. In the content template of the TabControl is a ListBox. The view gets bound to an object of the TabBindingViewModel class. This class has one property called Tabs which is an ObservableCollection of TabViewModel objects. The TabViewModel class has two properties: TabHeader and Guids. TabViewModel.TabHeader is a string that contains the text that will appear on the tab, and TabViewModel.Guids is an ObservableCollection of strings.

When bound, each TabViewModel in the TabBindingViewModel.Tabs collection should generate a tab in the TabControl object with the header of the tab being the TabViewModel.TabHeader property. The content of each tab should be the ListBox populated with the collection of strings in the TabViewModel.Guids collection.

Problem

This all appears to render/bind just fine, however if you change the state of a ListBox (for example scrolling or selecting an item) and then change tabs, it appears that the state carries over to the ListBox on the new tab that you just selected. This makes me assume that there is only one instance of the ListBox (instead of 5 separate instances) and when you change tabs, the data is the only thing that changes.

In another scenario, instead of binding a collection to a template, I explicitly define each TabItem object with it's own ListBox in the xaml. This time, when I click from tab to tab, each ListBox maintains it's own state.

Am I correct in my assumptions? And if so, how do I achieve the result described in the second scenario while still taking advantage of templating? (This is a simplified example. My real world content is much more complex.)

Thanks in advance for any help!

The source code for my example is listed below.

View Classes

1. TabBinding

<Window x:Class="TabBindingQuestion.View.TabBinding"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:vm="clr-namespace:TabBindingQuestion.ViewModel"
        Title="TabTemplateView" 
        Height="344" Width="618">
    <Window.Resources>
        <vm:TabBindingViewModel x:Key="Data" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Data}">
        <TabControl Width="Auto"
                    Height="Auto"
                    ItemsSource="{Binding Tabs}"
                    IsSynchronizedWithCurrentItem="True">
            <TabControl.ItemContainerStyle>
                <Style TargetType="TabItem">
                    <Setter Property="Header" Value="{Binding TabHeader}" />
                    <Setter Property="ContentTemplate">
                        <Setter.Value>
                            <DataTemplate>
                                <ListBox Width="Auto"
                                         Height="Auto"
                                         ItemsSource="{Binding Guids}" />
                            </DataTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </TabControl.ItemContainerStyle>
        </TabControl>
    </Grid>
</Window>

ViewModel Classes

2. ViewModelBase

using System.ComponentModel;

namespace TabBindingQuestion.ViewModel
{
    class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(object sender, string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(sender, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

3. TabBindingViewModel

using System.Collections.ObjectModel;

namespace TabBindingQuestion.ViewModel
{
    class TabBindingViewModel : ViewModelBase
    {
        #region Members

        private ObservableCollection<TabViewModel> _Tabs;
        public ObservableCollection<TabViewModel> Tabs
        {
            get { return _Tabs; }
            set
            {
                _Tabs = value;
                OnPropertyChanged(this, "Tabs");
            }
        }

        #endregion

        #region Constructor

        public TabBindingViewModel()
        {
            var tabs = new ObservableCollection<TabViewModel>();
            for (int i = 1; i <= 5; i++)
            {
                tabs.Add(new TabViewModel() { TabHeader = "Tab " + i.ToString() });
            }
            Tabs = tabs;
        }

        #endregion
    }
}

4. TabViewModel

using System;
using System.Collections.ObjectModel;

namespace TabBindingQuestion.ViewModel
{
    class TabViewModel : ViewModelBase
    {
        #region Members

        private string _TabHeader;
        public string TabHeader
        {
            get { return _TabHeader; }
            set
            {
                _TabHeader = value;
                OnPropertyChanged(this, "TabHeader");
            }
        }

        private ObservableCollection<string> _Guids;
        public ObservableCollection<string> Guids
        {
            get { return _Guids; }
            set
            {
                _Guids = value;
                OnPropertyChanged(this, "Guids");
            }
        }

        #endregion

        #region Constructors

        public TabViewModel()
        {
            var guids = new ObservableCollection<string>();
            for (int i = 1; i < 100; i++)
            {
                guids.Add(Guid.NewGuid().ToString());
            }
            Guids = guids;
        }

        #endregion
    }
}

回答1:


Yes the TabControl re-uses controls if they are the same when switching tabs. It also Unloads/Reloads controls as needed which causes unbound controls to be reset. For example, if Tab1 has a ListBox with the ItemA selected and you select ItemB and switch tabs to one without the listbox, when you go back to Tab1 ItemA is selected again.

Best thing to do is bind your UI properties to something in the code behind. For example, your TabControl might contain a list of TabItemViewModel and each ViewModel should contain properties representing the state of your UI, such as ListBox.SelectedItems or CheckBox.IsChecked.



来源:https://stackoverflow.com/questions/4157650/wpf-tabcontrol-templating

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!