【问题标题】:WPF Item Templates - TabControlWPF 项目模板 - TabControl
【发布时间】:2011-08-23 14:43:54
【问题描述】:

我正在编写一个应用程序,其中我使用一个选项卡控件,该控件将从一个选项卡开始打开,但允许用户打开多个其他选项卡。

打开的每个选项卡都应该有一个树形视图,当用户加载文件时,我使用数据绑定在其中填充。

我是 WPF 的新手,但我觉得好像有一种方法可以创建一个包含 TabItems 应包含的每个元素的模板。我怎样才能使用模板做到这一点?现在我的选项卡项目的 WPF 如下

<TabItem Header="Survey 1">
        <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
                  Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" />
 </TabItem>

【问题讨论】:

    标签: c# .net wpf templates xaml


    【解决方案1】:

    我想你想要这样的东西:

    <Window x:Class="TestWpfApplication.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <DataTemplate x:Key="TabItemTemplate">
            <TreeView Height="461" Name="treeView1" VerticalAlignment="Top" 
                        Width="625" Margin="0,0,6,0" ItemTemplateSelector="{StaticResource TreeviewDataSelector}" />
        </DataTemplate>
    
    </Window.Resources>
    <Grid>
        <TabControl ItemsSource="{Binding ListThatPowersTheTabs}"
                    ItemTemplate="{StaticResource TabItemTemplate}">
        </TabControl>
    </Grid>
    

    您基本上可以将可重用模板创建为静态资源,您可以通过它们的键名来引用它们。

    【讨论】:

      【解决方案2】:

      通常在这种情况下,我将 TabControl.ItemsSource 绑定到 ObservableCollect&lt;ViewModelBase&gt; OpenTabs,因此我的 ViewModel 负责根据需要添加/删除新标签。

      然后,如果您想要在每个 Tab 中添加某些内容,则覆盖 TabControl.ItemTemplate 并使用以下行指定在何处显示当前选定的 TabItem

      &lt;ContentControl Content="{Binding }" /&gt;

      如果您不需要在每个选项卡中设置某些内容,则无需覆盖 TabControl.ItemTemplate - 它会默认在选项卡中显示当前选择的 ViewModelBase

      我使用 DataTemplates 来指定要使用的视图

      <DataTemplate TargetType="{x:Type local:TabAViewModel}">
          <local:TabAView />
      </DataTemplate>
      
      <DataTemplate TargetType="{x:Type local:TabBViewModel}">
          <local:TabBView />
      </DataTemplate>
      
      <DataTemplate TargetType="{x:Type local:TabCViewModel}">
          <local:TabCView />
      </DataTemplate>
      

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-11
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2010-12-21
        相关资源
        最近更新 更多