C # WPF ComboBox - allow item selection only once in a list

I am using C #, WPF and trying to use MVVM. So I have an ObservableCollection of MyObjects. The list is displayed in the DataGrid, and one property MyObject is a static list of elements that is displayed in ComboBoxes on each row.

Now I would like to select an item on one line in this combo box, and if it was selected on another line before, the last selection should be removed to the default value. How can i do this? My MyObjectViewModel knows about changing its own "combobox", but how can it tell MainViewModel (which contains the ObservableCollection MyObjects) to change the last selected ComboBox from another MyObject?

+3
source share
1 answer

The best way to do this is to change the binding of the binding to ListCollectionViews, as this will allow you to control the cursor. The following is an example:

ViewModel

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

    namespace BindingSample
    {
        public class ViewModel
        {
            private string[] _items = new[] { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };

            public ViewModel()
            {
                List1 = new ListCollectionView(_items);
                List2 = new ListCollectionView(_items);
                List3 = new ListCollectionView(_items);

                List1.CurrentChanged += (sender, args) => SyncSelections(List1);
                List2.CurrentChanged += (sender, args) => SyncSelections(List2);
                List3.CurrentChanged += (sender, args) => SyncSelections(List3);
            }

            public ListCollectionView List1 { get; set; }

            public ListCollectionView List2 { get; set; }

            public ListCollectionView List3 { get; set; }

            private void SyncSelections(ListCollectionView activeSelection)
            {
                foreach (ListCollectionView view in new[] { List1, List2, List3 })
                {
                    if (view != activeSelection && view.CurrentItem == activeSelection.CurrentItem)
                        view.MoveCurrentTo(null);
                }
            }
        }
    }

View

<Window x:Class="ContextMenuSample.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">
    <StackPanel Orientation="Vertical">
        <ListBox ItemsSource="{Binding List1}" />
        <ListBox ItemsSource="{Binding List2}" />
        <ListBox ItemsSource="{Binding List3}" />        
    </StackPanel>
</Window>

This will allow you to select only one item. Now it is hardcoded, but can be easily more flexible for additional lists.

+1
source

All Articles