【问题标题】:Change ItemTemplate of XAML Listview programmatically in backend在后端以编程方式更改 XAML Listview 的 ItemTemplate
【发布时间】:2016-05-07 21:38:54
【问题描述】:

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


    【解决方案1】:

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

    public MainPage()
    {
        this.InitializeComponent();
    
        itemListView.ItemTemplate = (DataTemplate)Resources["DataTemplate2"];
    }
    

    【讨论】:

    • 当我读到你的回答时,我想:是的,我已经尝试过了.....但显然我没有:-(你的回答非常棒,非常感谢!
    • 我在代码后面(c#)中创建了网格和行和列内部,然后在行/列内部也创建并放置了边框和文本控件。现在我想把这个网格放在代码后面的 DataTemplate 中,然后将该 DataTemplate 分配给 Listview ItemTemplate。那怎么可能。请。在这里,您提到将 DT 分配给 ItemTemplate 但它来自 Resource ...并且我有一个动态值..所以我需要创建它动态并放置/设置值。
    【解决方案2】:

    有点老的问题,但首先在谷歌搜索中,所以,我添加我的答案 您可以按名称访问模板 为资源定义 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;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-08
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      相关资源
      最近更新 更多