WPF自动从上下文列出项目

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

假设我有一个A类。我已经创建了一个使用A作为DataContext的UserControle X.现在有B类.B类只包含一个填充A实例的List.B的实例是我当前View的DataContext。

在UserControle X的当前DataContext列表中显示A的所有实例的最佳方法是什么?

我需要价值转换器吗?或者有一种更简单的方法。

我试图保持抽象。如果我需要指定某些内容,请告诉我。

c# wpf user-controls itemtemplate
1个回答
1
投票

你可以使用带有ItemsControlItemTemplate。将ItemsControl绑定到公共收集属性,并将UserControl添加到ItemTemplate

<ItemsControl ItemsSource="{Binding TheListProperty}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- The UserControl will inherit the current item in 'TheListProperty' as its DataContext -->
            <local:UserControlX />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

确保没有明确设置DataContextUserControl。它应该从DataContext中的当前项目继承其ItemsControl

© www.soinside.com 2019 - 2024. All rights reserved.