繁体   English   中英

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

[英]Change ItemTemplate of XAML Listview programmatically in backend

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM