Confused about CollectionViewSource (SelectedItem not working in combos)

落花浮王杯 提交于 2019-12-01 20:27:20

I'm very sorry for wasting everyone's time, but setting IsSynchronizedWithCurrentItem="False" does work. I had also added a filter along with the sort, and the default selected values were not in the filtered list of items. Oops.

As for WHY I needed to explicitly turn IsSynchronizedWithCurrentItem off when I never normally do on standard collections, light is shed on MSDN

true if the SelectedItem is always synchronized with the current item in the ItemCollection; false if the SelectedItem is never synchronized with the current item; Nothing if the SelectedItem is synchronized with the current item only if the Selector uses a CollectionView. The default value is Nothing.

So in other words, if you use a CollectionView explicitly rather than using the default view on a normal collection, you get selection sync.

I havn't touched WPF in a while but I think that you need a different instances of CollectionViewSource for each combobox for the selected item to be maintained.

I think this is because the SelectedItem property is being bound to the CollectionViewSource object's selected item state property (I'm guessing that the View object has it) and the ComboBoxes all share the same source instance, thus their selected item are now synced.

So, just use different instances of CollectionViewSource for each of your ComboBoxes. You can still share the same source choices. You just need different VMs since your ComboBoxes should behave separately from each other.


Something like this (untested):

class EditStuffViewModel : ViewModelBase
{
    public EditStuffViewModel (ObservableCollection<Choice> choices)
    {
        ChoiceViews = new List<ICollectionView>();

        for (var i = 0; i < 10; i++) {
            var viewSource = new CollectionViewSource() { Source = choices };
            viewSource.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));

            ChoiceViews.Add(viewSource.View);
        }
    }

    public IList<ICollectionView> ChoiceViews
    {
        get; private set;
    }

    //snip other properties
}

Then change your ComboBoxes binding to bind to an element of ChoiceViews instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!