代码之家  ›  专栏  ›  技术社区  ›  Álvaro García

如何在列表框中绑定元组列表?

wpf
  •  0
  • Álvaro García  · 技术社区  · 7 年前

    <ListBox x:Name="list1" ItemsSource="{Binding MyListWithTuples}">
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <Label Content="{Binding value1}" />
                                        <Label Content="{Binding value2}" />
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
    

    在我的视图模型中,我有以下集合:

    private ObservableCollection<(decimal value1, decimal value2)> _myCollection= new ObservableCollection<(decimal value1, decimal value2)>();
            public ObservableCollection<(decimal vaule1, decimal value2)> MyCollection
            {
                get { return _myCollection; }
                set
                {
                    _myCollection= value;
                    base.RaisePropertyChangedEvent("MyCollection");
                }
            }
    

    但数据并没有显示出来。但是,如果将元组转换为字典,则可以绑定到键和值属性,并显示数据。但是我想避免把元组转换成字典。

    有什么方法可以将列表框绑定到元组列表吗?

    1 回复  |  直到 7 年前
        1
  •  4
  •   Clemens    7 年前

    不像 Tuple Class C# tuple types 只定义字段,不定义属性。所以不能将它们与WPF数据绑定一起使用。

    public ObservableCollection<Tuple<decimal, decimal>> MyCollection { get; }
    

    您可以使用以下XAML:

    <ListBox ItemsSource="{Binding MyCollection}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Label Content="{Binding Item1}" />
                    <Label Content="{Binding Item2}" />
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>