首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在后端以编程方式更改XAML列表视图的ItemTemplate

在后端以编程方式更改XAML列表视图的ItemTemplate
EN

Stack Overflow用户
提问于 2016-01-30 00:44:02
回答 2查看 3.9K关注 0票数 2

我在StackOverflow上读了这么多的帖子和很多博客文章,但是我的问题找不到一个有用的答案:我正在开发一个windows 10通用应用程序。我有一个使用项目模板的列表视图。现在,我添加了另一个项模板,并希望在应用程序启动时使用模板设置。不需要逐项执行,应该为所有项目添加模板。

代码语言:javascript
复制
<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>

做这件事最简单的方法是什么?我尝试了这么多选择,但都没有奏效:-(非常感谢!)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-01-30 10:21:09

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

代码语言:javascript
复制
public MainPage()
{
    this.InitializeComponent();

    itemListView.ItemTemplate = (DataTemplate)Resources["DataTemplate2"];
}
票数 4
EN

Stack Overflow用户

发布于 2020-05-02 05:12:31

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

代码语言:javascript
复制
  <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>

然后在后面的代码中以名称访问它(在一个无线电按钮更改上切换数据板)

代码语言:javascript
复制
    private void rbMeal_CheckedChanged(object sender, CheckedChangedEventArgs e)
    {
        lvProducts.ItemTemplate = (rbMeal.IsChecked) ? dtPerMeal : dtPerBatch;
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35096613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档