我有一个绑定到一个IList
的ViewModels的TabControl
。这IList
不会超过TabControl
的寿命而改变。
<TabControl ItemsSource="{Binding Tabs}" SelectedIndex="0" >
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem">
<Setter Property="Content" Value="{Binding}" />
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
每个视图模型具有在一个DataTemplate
指定的ResourceDictionary
。
<DataTemplate TargetType={x:Type vm:MyViewModel}>
<v:MyView/>
</DataTemplate>
每个在DataTemplate中指定的意见是资源密集型足以创造,我宁愿创建的每个视图只有一次,但是当我切换标签,相关视图的构造函数被调用。从我已阅读,这是为TabControl
预期的行为,但我不明白的机制是什么它调用构造函数。
我已经采取了看看a similar question which uses UserControl
s但解决方案提供有需要我绑定到的意见这是不可取的。
默认情况下,TabControl
共享一个面板来呈现它的内容。要做到你想要什么(和许多其他WPF开发),您需要延长TabControl
像这样:
TabControlEx.cs
[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : TabControl
{
private Panel ItemsHolderPanel = null;
public TabControlEx()
: base()
{
// This is necessary so that we get the initial databound selected item
ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
}
/// <summary>
/// If containers are done, generate the selected item
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
{
if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
UpdateSelectedItem();
}
}
/// <summary>
/// Get the ItemsHolder and generate any children
/// </summary>
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
ItemsHolderPanel = GetTemplateChild("PART_ItemsHolder") as Panel;
UpdateSelectedItem();
}
/// <summary>
/// When the items change we remove any generated panel children and add any new ones as necessary
/// </summary>
/// <param name="e"></param>
protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
{
base.OnItemsChanged(e);
if (ItemsHolderPanel == null)
return;
switch (e.Action)
{
case NotifyCollectionChangedAction.Reset:
ItemsHolderPanel.Children.Clear();
break;
case NotifyCollectionChangedAction.Add:
case NotifyCollectionChangedAction.Remove:
if (e.OldItems != null)
{
foreach (var item in e.OldItems)
{
ContentPresenter cp = FindChildContentPresenter(item);
if (cp != null)
ItemsHolderPanel.Children.Remove(cp);
}
}
// Don't do anything with new items because we don't want to
// create visuals that aren't being shown
UpdateSelectedItem();
break;
case NotifyCollectionChangedAction.Replace:
throw new NotImplementedException("Replace not implemented yet");
}
}
protected override void OnSelectionChanged(SelectionChangedEventArgs e)
{
base.OnSelectionChanged(e);
UpdateSelectedItem();
}
private void UpdateSelectedItem()
{
if (ItemsHolderPanel == null)
return;
// Generate a ContentPresenter if necessary
TabItem item = GetSelectedTabItem();
if (item != null)
CreateChildContentPresenter(item);
// show the right child
foreach (ContentPresenter child in ItemsHolderPanel.Children)
child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
}
private ContentPresenter CreateChildContentPresenter(object item)
{
if (item == null)
return null;
ContentPresenter cp = FindChildContentPresenter(item);
if (cp != null)
return cp;
// the actual child to be added. cp.Tag is a reference to the TabItem
cp = new ContentPresenter();
cp.Content = (item is TabItem) ? (item as TabItem).Content : item;
cp.ContentTemplate = this.SelectedContentTemplate;
cp.ContentTemplateSelector = this.SelectedContentTemplateSelector;
cp.ContentStringFormat = this.SelectedContentStringFormat;
cp.Visibility = Visibility.Collapsed;
cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
ItemsHolderPanel.Children.Add(cp);
return cp;
}
private ContentPresenter FindChildContentPresenter(object data)
{
if (data is TabItem)
data = (data as TabItem).Content;
if (data == null)
return null;
if (ItemsHolderPanel == null)
return null;
foreach (ContentPresenter cp in ItemsHolderPanel.Children)
{
if (cp.Content == data)
return cp;
}
return null;
}
protected TabItem GetSelectedTabItem()
{
object selectedItem = base.SelectedItem;
if (selectedItem == null)
return null;
TabItem item = selectedItem as TabItem;
if (item == null)
item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;
return item;
}
}
XAML
<Style TargetType="{x:Type controls:TabControlEx}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabControl}">
<Grid Background="{TemplateBinding Background}" ClipToBounds="True" KeyboardNavigation.TabNavigation="Local" SnapsToDevicePixels="True">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="ColumnDefinition0" />
<ColumnDefinition x:Name="ColumnDefinition1" Width="0" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition x:Name="RowDefinition0" Height="Auto" />
<RowDefinition x:Name="RowDefinition1" Height="*" />
</Grid.RowDefinitions>
<DockPanel Margin="2,2,0,0" LastChildFill="False">
<TabPanel x:Name="HeaderPanel" Margin="0,0,0,-1" VerticalAlignment="Bottom" Panel.ZIndex="1" DockPanel.Dock="Right"
IsItemsHost="True" KeyboardNavigation.TabIndex="1" />
</DockPanel>
<Border x:Name="ContentPanel" Grid.Row="1" Grid.Column="0"
Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
KeyboardNavigation.DirectionalNavigation="Contained" KeyboardNavigation.TabIndex="2" KeyboardNavigation.TabNavigation="Local">
<Grid x:Name="PART_ItemsHolder" Margin="{TemplateBinding Padding}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
注:我没有想出这个解决方案。它在规划论坛上分享了好几年,认为这是在现在的那些WPF的食谱书籍之一。最古老或原始的来源,我相信是PluralSight .NET blog post这answer on StackOverflow。
HTH,
通过Dennis
答案是一流的,而且非常漂亮,为我工作。但是,原来的文章在他的岗位提到现在下落不明,所以他的答案需要更多的信息,以便使用权开箱。
此答案是从一个角度MVVM点给出,并且VS 2013下进行了测试。
首先,有点背景。从Dennis
第一个答案的工作方式是,它隐藏和显示选项卡的内容,而不是破坏和重新创建表示标签内容,每次用户切换标签。
这具有以下优点:
TabControlEx.cs
// Copy C# code from @Dennis's answer, and add the following property after the
// opening "<Style" tag (this sets the key for the style):
// x:Key="TabControlExStyle"
// Ensure that the namespace for this class is the same as your DataContext.
这进入同一类别指向DataContext的。
XAML
// Copy XAML from @Dennis's answer.
这是一种风格。它进入XAML文件的标题。这种风格不会改变,并且被所有的标签控件简称。
原标签
您原来的标签可能是这个样子。如果切换标签页,你会发现,编辑框的内容就会消失,因为该选项卡的内容被丢弃,再重新创建。
<TabControl
behaviours:TabControlBehaviour.DoSetSelectedTab="True"
IsSynchronizedWithCurrentItem="True">
<TabItem Header="Tab 1">
<TextBox>Hello</TextBox>
</TabItem>
<TabItem Header="Tab 2" >
<TextBox>Hello 2</TextBox>
</TabItem>
自定义选项卡
改变标签使用我们的新的自定义的C#类,并使用Style
标签在我们的新的自定义样式点吧:
<sdm:TabControlEx
behaviours:TabControlBehaviour.DoSetSelectedTab="True"
IsSynchronizedWithCurrentItem="True"
Style="{StaticResource TabControlExStyle}">
<TabItem Header="Tab 1">
<TextBox>Hello</TextBox>
</TabItem>
<TabItem Header="Tab 2" >
<TextBox>Hello 2</TextBox>
</TabItem>
现在,当你切换标签,你会发现,编辑框的内容被保留,这证明了一切工作很好。
更新
这个解决方案工作得很好。然而,要做到这一点更加模块化和MVVM友好的方式,它使用附加的行为来达到同样的效果。见Code Project: WPF TabControl: Turning Off Tab Virtualization。我加入这个作为一个附加的应答。
更新
如果你碰巧使用DevExpress
,您可以使用CacheAllTabs
选项来达到同样的效果(这关闭选项卡虚拟化):
<dx:DXTabControl TabContentCacheMode="CacheAllTabs">
<dx:DXTabItem Header="Tab 1" >
<TextBox>Hello</TextBox>
</dx:DXTabItem>
<dx:DXTabItem Header="Tab 2">
<TextBox>Hello 2</TextBox>
</dx:DXTabItem>
</dx:DXTabControl>
为了记录在案,我不与DevExpress的下属,我敢肯定,Telerik的具有相当。
更新
Telerik的确实有相同的:IsContentPreserved
。由于在下面的评论@Luishg。
通过@Dennis这种现有的解决方案(与其他注释通过@Gravitas)的作品非常好。
然而,还有另一种解决方案,它是更加模块化和MVVM友好的,因为它使用附加的行为来达到同样的效果。
见Code Project: WPF TabControl: Turning Off Tab Virtualization。由于作者是路透技术领先,代码可能是固体。
演示代码真的放在一起,它显示了一个普通的TabControl,沿着一个与附加的行为。
请从这个职位检查我的答案左右。希望能解决这个问题,但它是一个有点过了MVVM路。 Link
有一个不是很明显,但优雅的解决方案。其主要思想是手动生成的VisualTree用于通过自定义转换器的TabItem的Content属性。
定义一些资源
<Window.Resources>
<converters:ContentGeneratorConverter x:Key="ContentGeneratorConverter"/>
<DataTemplate x:Key="ItemDataTemplate">
<StackPanel>
<TextBox Text="Try to change this text and choose another tab"/>
<TextBlock Text="{Binding}"/>
</StackPanel>
</DataTemplate>
<markup:Set x:Key="Items">
<system:String>Red</system:String>
<system:String>Green</system:String>
<system:String>Blue</system:String>
</markup:Set>
</Window.Resources>
哪里
public class ContentGeneratorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var control = new ContentControl {ContentTemplate = (DataTemplate) parameter};
control.SetBinding(ContentControl.ContentProperty, new Binding());
return control;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotImplementedException();
}
和设置是这样的
public class Set : List<object> { }
然后,而不是传统的使用的ContentTemplate属性
<TabControl
ItemsSource="{StaticResource Items}"
ContentTemplate="{StaticResource ItemDataTemplate}">
</TabControl>
我们应该通过以下方式指定ItemContainerStyle
<TabControl
ItemsSource="{StaticResource Items}">
<TabControl.ItemContainerStyle>
<Style TargetType="TabItem" BasedOn="{StaticResource {x:Type TabItem}}">
<Setter Property="Content" Value="{Binding Converter={StaticResource ContentGeneratorConverter}, ConverterParameter={StaticResource ItemDataTemplate}}"/>
</Style>
</TabControl.ItemContainerStyle>
</TabControl>
现在,尝试到两个变化比较一下,看标签切换过程中的差异成ItemDataTemplate文本框的行为。