【问题标题】:Dynamically change DataTemplate for a ListView at Runtime在运行时动态更改 ListView 的 DataTemplate
【发布时间】:2015-11-03 14:26:14
【问题描述】:

我有 2 个 DataTemplates 用于在单个 ListView 中显示 ClassA 或 ClassB 的内容;选择哪个模板将基于用户的 RadioButton 选择。

是否可以在运行时根据用户输入动态更改 ListView(在 XAML 中)的 ItemTemplate?

sn-p 示例代码:

XAML 页面:

<Page...>
    <Page.Resources>
        <DataTemplate x:Key="ClassAListViewItemTemplate" x:DataType="vm:ClassA" ... />
        <DataTemplate x:Key="ClassBListViewItemTemplate" x:DataType="vm:ClassB" ... />    
    </Page.Resources>
    <RelativePanel>
        <RadioButton Content="ClassA" ... />
        <RadioButton Content="ClassB" ... />
        <ListView DataContext="{Binding Path=MainViewModel}"
                  ItemsSource="{Binding ListOfClassAOrB, Mode=TwoWay}"
                  ItemTemplate="{StaticResource ClassAListViewItemTemplate}"/>
    </RelativePanel>
</Page>

我已将代码精简为基本要素,但我希望能够在运行时更改以下内容:

ItemTemplate="{StaticResource ClassAListViewItemTemplate}"

我见过使用 Style.Triggers 的经典 WPF 应用程序的解决方案,但这些不适用于 UWP

Marco Minerva 在Adaptive Triggers, RelativePanel and DataTemplate in the Universal Windows Platform 上的博客谈到在 DataTemplates 中使用 UserControls 来使用自适应触发器修改视觉状态,但这并没有考虑到根据用户输入切换模板

我找到的最接近我的问题的答案是他写的另一个博客“Dynamically choose DataTemplate in WinRT”,其中涉及代码隐藏元素 - 但它似乎只是一个 if 语句 - 但它是我拥有的最干净的解决方案到目前为止,我想在 XAML 中复制什么

谢谢

【问题讨论】:

  • 也许this question 它的回答会有所帮助。
  • 嗨 Romasz,感谢您的回复,但您链接的建议问题/答案仍然需要创建一个带有逻辑的 DataTemplateSelector 子类 - 我更多的是寻找一种避免陷入 C# 代码的解决方案- 如果这是可能的。 DataTemplateSelector 子类添加的唯一内容是 If 语句,我认为在 XAML 中可能有一种简洁的方法
  • 我需要的是一个类似于this question 的已接受答案但不使用样式触发器的解决方案,因为它们在 UWP 中不可用

标签: xaml winrt-xaml uwp


【解决方案1】:

您需要使用覆盖 Data 模板的 SelectTemplateCore。像这样更改您的视图模型。 下面的代码会帮助你。

public class SampleViewModel : DataTemplateSelector
{
    public DataTemplate ClassAListViewItemTemplate{ get; set; }
    public DataTemplate ClassBListViewItemTemplate{ get; set; }

    protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
    {
        var itemsData = item as SampleClass; // add your Data class 
        if (itemsData.IsAddButton == false) // define any property to select the datatemplate
        {
            return ClassAListViewItemTemplate;
        }
        else
        {
            return ClassBListViewItemTemplate;
        }
    }
}

将您的两个数据模板添加到一个键中,并将键提供给 gridview 中的 ItemTemplateSelector 属性。

<viewModels:SampleViewModel x:Key="FeedbackTempateSelector"
    ClassAListViewItemTemplate="{StaticResource ClassAListViewItemTemplate}"
    ClassBListViewItemTemplate="{StaticResource ClassBListViewItemTemplate}">

</viewModels:SampleViewModel>

【讨论】:

  • 在返回语句中它说:不能将类型 'string' 隐式转换为 'Windows.Ui.Xaml.DataTemplate'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-02
  • 2023-03-30
相关资源
最近更新 更多