Skip to main content
 首页 » 编程设计

c#之WPF:具有多个数据模板的 TabControl

2024年02月05日13over140

我有一个带有多个 DataTemplate 的 TabControl。第一个 DataTemplate 将用于搜索,第二个将用于显示从该搜索中获得的项目。我的 XAML 代码如下:

 <UserControl.Resources> 
    <!--First template--> 
    <DataTemplate> 
        <!-- I will have a DataGrid here--> 
    </DataTemplate> 
 
    <!--Second template--> 
    <DataTemplate > 
         <!-- I will have details of one item of the DataGrid--> 
    </DataTemplate> 
</UserControl.Resources> 
 
 
<TabControl ItemsSource="{Binding }"/> 

我想要完成的是,在 TabControl 中,第一个选项卡将包含第一个 DataTemplate(搜索模板),当我双击我的DataGrid,将添加一个包含该行详细信息的选项卡(换句话说,一个包含第二个模板的选项卡)。

由于我使用的是 MVVM,所以我想创建两个 UserControl,每个模板一个,然后捕获双击事件,但在此之后我没有知道如何添加选项卡,因为现在我的搜索模板是一个 UserControl,与包含 TabControl 的模板分开。

那我该怎么做呢?

更新:

当我阅读答案时,我认为我在陈述问题时不是很清楚。 我的问题是如何通过捕获第一个模板中的双击事件来使用第二个模板添加选项卡。我独立添加两个模板没有任何问题。

请您参考如下方法:

与其创建两个 UserControl,不如创建和使用 DataTemplateSelector 以切换不同的 DataTemplate。

基本上,创建一个继承自 DataTemplateSelector 的新类并覆盖 SelecteTemplate 方法。然后在 XAML 中声明它的一个实例(很像一个值转换器),然后将它应用于 TabControl 的 ContentTemplateSelector 属性。

More info can be found here .