开发者

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.DataCon开发者_开发技巧text+=myViewModel2.sessions;

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜