1

I have a listbox like this:

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

In my view model I have this collection:

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");
            }
        }

But the data isn't show. However if I convert the tuple to a dictionary, I can bind to Key and Value properties and the data is shown. But I would like to avoid to convert the tuple into a dictionary.

Are there some way to bind the listbox to a list of tuples?

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193
  • Does this answer your question? [Is it possible to bind to a ValueTuple field in WPF with C#7](https://stackoverflow.com/questions/43208852/is-it-possible-to-bind-to-a-valuetuple-field-in-wpf-with-c7) – StayOnTarget Apr 12 '22 at 15:37

1 Answers1

6

Unlike the Tuple Class, the new C# tuple types only define fields, but no properties. So you can't use them with WPF data binding.

However, with

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

you could use this XAML:

<ListBox ItemsSource="{Binding MyCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding Item1}" />
                <Label Content="{Binding Item2}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
Clemens
  • 123,504
  • 12
  • 155
  • 268