如何在WPF中的模板化TabItem上获得关闭按钮?

Rus*_*uss 2 wpf styles datatemplate .net-3.5

我有一个TabControlTabItems的DataTemplat主编.该模板似乎正常工作,因为我要在其中显示的用户控件TabItem正确显示.

我不确定的是如何让"x"显示出来,TabItem因此我可以关闭每个标签,因为它们是通过模板动态生成的.

作为WPF的新手,我开始接受许多概念,但是TabControl给了我很多麻烦,所以我很可能让模板可行,但不可维护.

这就是我所拥有的,我希望能够关闭每一个TabControl.我还需要能够在TabControl关闭时触发自定义事件.

<UserControl x:Class="Russound.Windows.UI.UserControls.CallLog.CaseReaderWpf"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:CallLog="clr-namespace:Russound.Windows.UI.UserControls.CallLog"
    Height="637" Width="505">

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Russound.Windows;component/UI/RussoundDictionary.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <TabControl x:Name="tabCases" >
        <TabControl.ItemTemplate>
            <DataTemplate DataType="{x:Type TabItem}">
                <StackPanel>
                    <TextBlock Text="{Binding Path=Id}" />
                </StackPanel>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate DataType="{x:Type TabItem}">
                <CallLog:CaseReadOnlyDisplay DataContext="{Binding}" />
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

Taw*_*ani 7

查看Josh Smith撰写的这篇MSDN文章.这是一个很好的解决方案.

使用Model-View-ViewModel设计模式的WPF应用程序

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

<!-- 
This template explains how to render 
a tab item with a close button.
-->
<DataTemplate x:Key="ClosableTabItemTemplate">
<DockPanel Width="120">
  <Button 
    Command="{Binding Path=CloseCommand}"
    Content="X"
    Cursor="Hand"
    DockPanel.Dock="Right"
    Focusable="False"
    FontFamily="Courier" 
    FontSize="9"
    FontWeight="Bold"  
    Margin="0,1,0,0"
    Padding="0"
    VerticalContentAlignment="Bottom"
    Width="16" Height="16" 
    />
  <ContentPresenter 
    Content="{Binding Path=DisplayName}" 
    VerticalAlignment="Center" 
    />
</DockPanel>
</DataTemplate>

<!--
This template explains how to render the 'Workspace' content area in the main window.
-->
<DataTemplate x:Key="WorkspacesTemplate">
<TabControl 
  IsSynchronizedWithCurrentItem="True" 
  ItemsSource="{Binding}" 
  ItemTemplate="{StaticResource ClosableTabItemTemplate}"
  Margin="4"
  />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

  • 我想知道为什么他将TabItem的标题绑定到DisplayName而不是TabItem的Header属性. (3认同)
  • 虽然暂时我认为这是"黑暗艺术"的一部分,但它正在经过相当多的阅读和游戏之后才开始工作.我确信我只需要习惯这种思维方式,只需要接受这一点作为Winforms转换为WPF的一部分. (2认同)