簡體   English   中英

WPF:如何在ItemsControl中使用兩個不同的控件?

[英]WPF: How do I use two different controls in an ItemsControl?

我有一個WPF ItemsControl,它的ItemsSource綁定到MVVM中可觀察的視圖模型集合。 ItemTemplate設置為我想要的用戶控件。 但是,有些情況下我想要另一個控件而不是XAML中指定的控件。

我怎么能輕松做到這一點?

使用DataTemplates將視圖模型映射到視圖:

<ItemsControl ItemsSource="{Binding SomeCollectionOfViewModels}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type local:FirstViewModel}">
            <Label>Foo</Label>
        </DataTemplate>

        <DataTemplate DataType="{x:Type local:SecondViewModel}">
            <Label>Bar</Label>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

如果我了解你有一個包含兩種不同類型對象的集合,並且你想要2個不同的模板。 您可以為每個對象類型構建一個datatemplate,並讓WPF根據對象類型呈現正確的模板。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM