c# - 根据 ViewModel 类型为 ItemsControl 选择 DataTemplate

标签 c# wpf xaml mvvm

我试图让我的 ItemsControl 根据其 viewModel 类型显示具有不同模板的项目。乍一看,我认为它可以像我们通常在 ContentControl 中做的那样:

 <ItemsControl ItemsSource="{Binding MyViewModelCollection}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <WrapPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
            <ItemsControl.ItemTemplate>
                <DataTemplate DataType="{x:Type myNameSpace:myViewModel1}">
                     <myNameSpace:myControl2/>
                </DataTemplate>
                <DataTemplate DataType="{x:Type myNameSpace:myViewModel2}">
                     <myNameSpace:myControl2/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>

但不幸的是,您不能在 ItemsControl.ItemTemplate 中有两个 DataTemplate。 我找到了一个小技巧来做到这一点。

最佳答案

在您的 XAML 代码中,只需将 ItemsControl.ItemTemplate 标记替换为 ItemsControl.Resources 即可。

<ItemsControl ItemsSource="{Binding MyViewModelCollection}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type myNameSpace:myViewModel1}">
             <myNameSpace:myControl2/>
        </DataTemplate>
        <DataTemplate DataType="{x:Type myNameSpace:myViewModel2}">
             <myNameSpace:myControl2/>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

关于c# - 根据 ViewModel 类型为 ItemsControl 选择 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34768554/

相关文章:

c# - Gridview 行编辑需要在编辑模式下锁定排序不允许

c# - 在运行时向 WPF DataGrid 添加行和列

c# - 序列化 WPF DataTemplates 和 {Binding Expressions}(来自 PowerShell?)

WPF DockPanel IsMouseOver 仅在将鼠标悬停在子控件上时触发

c# - 在 UWP 中使用 DataTriggerBehavior 更改 ContentTemplate

c# - 从 Oracle 到 MySql 数据库的 DateTime 值

c# - 批量保存到 MongoDB C# 驱动程序

c# - LINQ 是否缓存计算值?

WPF MVVM-Light 如何在ViewModel中使用传递的DragEventArgs

c++ - Visual Studio 2012 中的 Visual C++ 使用 XAML