如何在 ObservableCollection<MyClass> 中绑定一个 List<KeyValuePair<MyClass2,int>>?

How I can bind a List<KeyValuePair<MyClass2,int>> inside ObservableCollection<MyClass>?

我有一个 class BindingList<KeyValuePair<BoardElement,int>>:

public class Binding
{
    public List<KeyValuePair<BoardElement, int>> Outputs { get; set; }
}

而classBoardElement包含属性Name:

public class BoardElement
{
    private string Name { get; set; }
}

我有 ObservableCollection<Binding>.

现在,我想要 Binding Name <- BoardElement <- KeyValuePair <- Outputs.

我尝试这样的事情

<ListBox.ItemTemplate>
    <DataTemplate>
        <StackPanel  Orientation="Horizontal">
            <TextBlock Text="{Binding Outputs.Key.Name}" SelectedIndex="{Binding SelectedType}"  />
        </StackPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

但它不起作用,因为它需要在此处 Binding Outputs.?.Key.Name 的路径中添加一些内容。 它仅在我选择第一个元素 Binding Outputs[0].Key.Name 时有效,但我想为每个 KeyValuePair 创建一个 TextBlock 并为它们带来一个 Name

public ObservableCollection<Binding> B { get; set; }

public MainWindow()
{
    var a = new Binding();
    
    a.Input = new BoardElement("D1");
    a.Outputs = new List<KeyValuePair<BoardElement, int>>();

    var c = new BoardElement("D2");
    a.Outputs.Add(new KeyValuePair<BoardElement, int>(c, 7));
    
    B = new ObservableCollection<Binding>();
    B.Add(a);
    
    ListOfBindngs.ItemsSource = B;
}

所以我想知道 Binding 如何在另一个集合中创建集合? 我只能按索引选择([0]、[1] 等...),但我想全部显示出来

您有一个嵌套列表:Binding 的列表,每个列表都有 KeyValuePair.

的列表

选项 A,嵌套列表框:

<ListBox SelectedIndex="{Binding SelectedType}" x:Name="ListOfBindngs" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel  Orientation="Horizontal">
                <ListBox ItemsSource="{Binding outputs}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Key.Name}" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

选项 B,转换器:

public class ConvertOutputs : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var list = (List<KeyValuePair<BoardElement, int>>)value;
        return string.Join(", ", list.Select(x => x.Key.Name));
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => null;
}

在xaml中:

<ListBox SelectedIndex="{Binding SelectedType}" x:Name="ListOfBindngs" >
    <ListBox.Resources>
        <local:ConvertOutputs x:Key="ConvertOutputs"/>
    </ListBox.Resources>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel  Orientation="Horizontal">
                <TextBlock Text="{Binding outputs, Converter={StaticResource ConvertOutputs}}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>