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

问题描述 投票:2回答:2

我在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>

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

c# xaml listview uwp windows-10-universal
2个回答
3
投票

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

public MainPage()
{
    this.InitializeComponent();

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

0
投票

有点老问题,但首先在Google搜索中,所以,我添加了我的答案您可以按名称访问模板定义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;
    }
© www.soinside.com 2019 - 2024. All rights reserved.