Cris
Cris

Reputation: 12194

WPF: can i concatenate a DataBinding property?

i have a ListBox that has a DataContext property populated from class items

lb.DataContext= myViewModel.sessions;

I need to "concatenate" this DataContext from other class items, such as:

 lb.DataContext+=myViewModel2.sessions;

that naturelly does not work. Is there a way to add items to an existing DataContext?

Upvotes: 1

Views: 325

Answers (1)

Wonko the Sane
Wonko the Sane

Reputation: 10813

In your ViewModel, simply create another collection that is the concatenation of the two collections, and bind to that.

For a simple example, here is a partial ViewModel (note that I used ints, but you'll have to substitute whatever your Sessions object is):

private List<int> sessionList1 = new List<int>();
private List<int> sessionList2 = new List<int>();

public MyViewModel()
{
    for (int i = 0; i < 10; i++)
        sessionList1.Add(i);
    for (int i = 10; i < 20; i++)
        sessionList2.Add(i);
}

public ReadOnlyObservableCollection<int> AllSessions
{
    get
    {
        ObservableCollection<int> combinedList = 
            new ObservableCollection<int>(sessionList1.Concat(sessionList2));
        return new ReadOnlyObservableCollection<int>(combinedList);
    }
}

And then, assuming that the DataContext of my View is bound to MyViewModel:

        <ListBox ItemsSource="{Binding AllSessions}" />

You will need to come up with the right collection to return (i.e. probably either ObservableCollection or ReadOnlyObservableCollection), and you'll need to concatenate your sessions appropriately, but this should get you going.

Upvotes: 1

Related Questions