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

时间:2016-01-30 00:44:02

标签: c# xaml listview uwp windows-10-universal

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

最简单的方法是什么?我已经尝试了很多选项,但没有一个能够正常工作:-( 非常感谢!

2 个答案:

答案 0 :(得分:2)

您可以在代码中设置ItemTemplate

public MainPage()
{
    this.InitializeComponent();

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

答案 1 :(得分:0)

有点老问题了,但是首先在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;
    }
相关问题