【问题标题】:How to have multiple datatemplates in UWP ListView (x:bind)如何在 UWP ListView (x:bind) 中拥有多个数据模板
【发布时间】:2018-10-27 23:33:25
【问题描述】:

我坚持使用我的 UWP 应用程序,我正在尝试使用 {x:bind} 而不是旧的 WPF 方式 {binding name} 遵循 MVVM 原则

但我坚持自己的想法/开发,我正在尝试在 ListView(或 GridView)中插入多个 DataTemplate。

我想做这样的事情作为例子:

            <ListView.ItemTemplate>
                <DataTemplate x:DataType="localModels:Cars">
                    <StackPanel Orientation="Vertical">
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="Name:" />
                            <TextBox Text="{x:Bind Name}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
                <!-- Here is the second DataTemplate which isn't allowed in UWP -->
               <DataTemplate x:DataType="localModels:Bikes">
                    <StackPanel Orientation="Vertical">
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="Name:" />
                            <TextBox Text="{x:Bind Name}" />
                        </StackPanel>
                    </StackPanel>
                </DataTemplate>
            </ListView.ItemTemplate>

如您所见,我在 ListView.ItemTemplate 中有 2 个 DataTemplate:汽车和自行车。

不确定这是否相关:Cars.cs 继承自 Bike.cs 父级。

我真的不明白为什么 UWP 在 ListView.ItemTemplate 中不接受超过 1 个 DataTemplate。因为我真的希望我的 ListView 显示尽可能多的数据。

在 UWP 和 {x:bind} 中解决这个问题的方法是什么?

【问题讨论】:

    标签: c# xaml uwp xbind


    【解决方案1】:

    您可以使用DataTemplateSelector 来确定应根据您的数据类型选择哪个数据模板。 Here你可以找到一个例子。

    【讨论】:

    • 谢谢!你认为我应该把 DataTemplate 类放在哪里?在视图中还是在其他地方?
    • 您的意思是DataTemplate 资源?如果您还想在其他地方重用它们,那么您可以将它们放入 App.Resources,否则我会将它们放入最近的使用位置。
    猜你喜欢
    • 2018-10-21
    • 2016-11-26
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 2020-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多