在后端以编程方式更改 XAML 列表视图的项模板



我已经阅读了很多关于StackOverflow的帖子和许多博客条目,但找不到我的问题的有效答案:我正在开发一个Windows 10通用应用程序。我有一个使用项目模板的列表视图。现在,我添加了另一个项模板,并希望使用模板进行设置,以便在应用程序启动时使用。无需逐项执行,应为所有项目添加模板。

<Page.Resources>
    <DataTemplate x:Key="DataTemplate1">
        (...)
    </DataTemplate>
    <DataTemplate x:Key="DataTemplate2">
        (...)
    </DataTemplate>
</Page.Resources>
<ListView
        x:Name="itemListView"
        AutomationProperties.AutomationId="ItemsListView"
        AutomationProperties.Name="Items"
        TabIndex="1"
        Grid.Column="0"
        IsSwipeEnabled="False" HorizontalContentAlignment="Stretch"
        SelectionChanged="ItemListView_SelectionChanged" IsSynchronizedWithCurrentItem="False" 
        ItemsSource="{Binding FeedItems}" ItemTemplate="{StaticResource DataTemplate1}" Margin="0,60,0,10" Grid.RowSpan="2">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>

最简单的方法是什么?我尝试了很多选择,但没有一个有效:-(非常感谢!

您可以在代码中设置ItemTemplate

public MainPage()
{
    this.InitializeComponent();
    itemListView.ItemTemplate = (DataTemplate)Resources["DataTemplate2"];
}

有点老的问题,但在谷歌搜索中首先,所以,我添加了我的答案您可以按名称访问模板定义资源的 x:名称

  <ContentPage.Resources>
    <ResourceDictionary>
        <DataTemplate x:Key="dtPerMeal" x:Name="dtPerMeal">
            <TextCell Text="{Binding Product.Name}" Detail="{Binding TotalWeight}" />
        </DataTemplate>
        <DataTemplate x:Key="dtPerBatch" x:Name="dtPerBatch">
            <TextCell Text="{Binding Product.Name}" Detail="0" />
        </DataTemplate>
    </ResourceDictionary>
</ContentPage.Resources>

然后在代码隐藏中按名称访问它(在单选按钮更改时切换数据模板)

    private void rbMeal_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        lvProducts.ItemTemplate = (rbMeal.IsChecked) ? dtPerMeal : dtPerBatch;
    }

最新更新