简体   繁体   中英

Can you bind a listbox to a list of tuples in WPF

If I have a List<Tuple<DateTime,DateTime>> can I bind that to list box in wpf? I know of course I can bind to dictionaries or whatever but in this cause I need to send back a list that could possible have identical values so it makes sense (or seems to) make sense to have a list of tuples? Anyone got any thoughts?

Yes, you can bind a ListBox to a collection of Tuples. However, unless there's a reason not to do so, I would have a collection of your own type, as the properties exposed on the Tuple type are not particularly descriptive.

Sure, you can bind to it. I threw together the following code behind:

public partial class MainWindow : Window
{
    private readonly ObservableCollection<Tuple<DateTime, DateTime>> _dates = new ObservableCollection<Tuple<DateTime,DateTime>>();
    public ObservableCollection<Tuple<DateTime, DateTime>> Dates { get { return _dates; } }

    public MainWindow()
    {
        DataContext = this;
        InitializeComponent();
        PopulateList();
    }

    private void PopulateList()
    {
        _dates.Add(new Tuple<DateTime, DateTime>(DateTime.Now, DateTime.Now));
        _dates.Add(new Tuple<DateTime, DateTime>(DateTime.Now, DateTime.Now));
        _dates.Add(new Tuple<DateTime, DateTime>(DateTime.Now, DateTime.Now));
    }
}

And XAML:

<Window x:Class="GuiScratch.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding Dates}"/>

    </Grid>
</Window>

When I run that, I see a list of items with two datetimes concatenated as list members.

That said, whether you want to do this or not probably depends more on specific context. If the need to have very pluggable binding types makes sense (ie date time may change to string or int), this may be a good option. If you don't, I'd say you'd be better off binding to something more expressive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM