在后端以编程方式更改 XAML Listview 的 ItemTemplate

Change ItemTemplate of XAML Listview programmatically in backend

我在 Whosebug 上阅读了很多帖子和很多博客条目,但找不到我的问题的有效答案: 我正在开发 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>

最简单的方法是什么?我尝试了很多选项,其中 none 确实有效:-( 非常感谢!

您可以在后面的代码中设置ItemTemplate

public MainPage()
{
    this.InitializeComponent();

    itemListView.ItemTemplate = (DataTemplate)Resources["DataTemplate2"];
}

有点老的问题,但首先在 google 搜索中,所以,我添加我的答案 您可以按名称访问模板 为资源

定义x:name
  <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;
    }