0

I'm trying to create a UserControl to show a ListBox (which I want to bind to a collection in the view model later) such that each item is displayed in a ComboBox (which allows for its drop-down menu to be opened and a different value to be selected). I also want to ensure that no value can be selected twice, and I want to add a button to create additional list items.

My idea is to have each DataTemplate for the ListBox contain a CollectionViewSource in its resources, filter that, and then bind the combo box to the filtered values. My problem is that I don't understand how I can get the bindings to work in this scenario -- everything works fine as long as my bindings are one-way, but the instant I make the ComboBoxes bind two-way I get an exception telling me I need to have a Path set for two-way bindings to work.

My XAML (slightly abridged for clarity):

<UserControl x:yadayada x:Name="MultiSelectList">
<Grid>
    <ListBox ItemsSource="{Binding ElementName=MultiSelectList, Path=ChosenItems, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <ComboBox Loaded="FrameworkElement_OnLoaded" DropDownOpened="ComboBox_OnDropDownOpened">
                    <ComboBox.Resources>
                        <CollectionViewSource Source="{Binding ElementName=MultiSelectList, Path=AllItems}" x:Key="Src" />
                    </ComboBox.Resources> 
                    <ComboBox.ItemsSource>
                        <Binding Source="{StaticResource Src}" />
                    </ComboBox.ItemsSource>
                </ComboBox>
                <!-- uncommenting the following line crashes the program -->
                <!-- <ComboBox.SelectedValue><Binding></Binding></ComboBox.SelectedValue> -->
            </DataTemplate> 
        </ListBox.ItemTemplate>
    </ListBox>
    <Button Content="New" Click="NewButton_Pressed"/>
</Grid>

The code behind:

using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace WPFCentralOffice.UserControls
{
    public class Element : IEquatable<Element>
    {
        public int ID { get; set; }
        public string Caption { get; set; }

        public bool Equals(Element other)
        {
            return ID == other.ID;
        }

        public override string ToString()
        {
            return ID + " " + Caption;
        }
    }

    public partial class MultiSelectListUserControl : UserControl
    {
        public ObservableCollection<Element> ChosenItems
        {
            get { return (ObservableCollection<Element>)GetValue(ChosenItemsProperty); }
            set { SetValue(ChosenItemsProperty, value); }
        }

        public ObservableCollection<Element> AllItems
        {
            get { return (ObservableCollection<Element>)GetValue(AllItemsProperty); }
            set { SetValue(AllItemsProperty, value); }
        }

        public static DependencyProperty AllItemsProperty = DependencyProperty.Register(
            "AllItems",
            typeof(ObservableCollection<Element>),
            typeof(MultiSelectListUserControl));

        public static DependencyProperty ChosenItemsProperty = DependencyProperty.Register(
            "ChosenItems",
            typeof(ObservableCollection<Element>),
            typeof(MultiSelectListUserControl));

        public void NewButton_Pressed(object sender, RoutedEventArgs e)
        {
            if (!AllItems.Any() || AllItems.Count == ChosenItems.Count)
            {
                return;
            }

            var elem = AllItems.First(x => ChosenItems.All(y => x.ID != y.ID));
            ChosenItems.Add(elem);
        }

        public MultiSelectListUserControl()
        {
            InitializeComponent();
            SetValue(AllItemsProperty, new ObservableCollection<Element>());
            SetValue(ChosenItemsProperty, new ObservableCollection<Element>());
        }

        private void ComboBox_OnDropDownOpened(object sender, EventArgs e)
        {
            var c = (ComboBox)sender;
            c.Items.Filter = x => ChosenItems.All(y => ((Element)x).ID != y.ID) || ((Element)c.SelectedValue).ID == ((Element)x).ID;
        }
    }
}

Not only does this not work, it also feels like a very complicated way of achieving what I want. Is there an easier way of having a list of combo boxes with different values? Or can somebody give me pointer such that I can implement this properly?

10
  • "I also want to ensure that no value can be selected twice" do you mean in the editable combo boxes? Dec 15, 2015 at 19:21
  • I want no two combo boxes to have the same value (each value will only appear in the list of acceptable values once). The combo boxes should not be editable as text boxes. Dec 16, 2015 at 8:55
  • 1
    I don't understand "such that each item is displayed as a ComboBox (and can be edited)" if that's the case. At any rate, what you need then is for each of your list items to have its own list of items, and your parent VM needs to have the master list, and a list of the selected ones. When any selection changes, every child re-filters its list to include a) all non-selected items, plus b) its own selected item. This is an unusual requirement and there isn't going to be a simple canned solution in XAML. Dec 16, 2015 at 17:34
  • Sorry if I was unclear, I will edit the original posting. Can you please elaborate on what you mean by "what you need then is for each of your list items to have its own list of items"? Should I have something like a ObservableCollection<ObservableCollection<Element>> and bind to that, such that the outer observable collection contains exactly one element per combo box, and each inner collection one item per selectable value in that combo box? Dec 16, 2015 at 19:18
  • 1
    Each Element in the listbox is displayed using an item template. In the item template for each Element, there is a ComboBox. The ItemsSource property for that ComboBox is bound to an Items property that belongs to Element. Each element returns a filtered list of items which excludes anything selected, except its own currently selected item. Element.Items is an IEnumerable. Element will have to implement INotifyPropertyChanged to notify the UI that its Items have changed. When any selection changes, Items changes for all Elements, so they need to communicate via MultiSelectList. Dec 16, 2015 at 20:10

1 Answer 1

0

I finally got it to work by @Ed Plunkett's suggestion to use a proxy object that the ComboBoxes bind to. This allows me to refresh the available items for each ComboBox when relevant actions (like adding a new list item or selecting a different value in a combo box) are triggered, simply by replacing the AvailableItems property value on each ComboBoxBindingSource.

This also allows the XAML to be much cleaner, since each ComboBox now has a proper binding:

<UserControl x:foobar x:Name="MultiSelectList">
    <Grid>
        <ListBox ItemsSource="{Binding ElementName=MultiSelectList, Path=ComboBoxBindingSources, Mode=TwoWay}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <ComboBox ItemsSource="{Binding Path=AvailableElements}" SelectedValue="{Binding Path=SelectedElement}" SelectionChanged="ComboBox_SelectionChanged" />
                </DataTemplate> 
            </ListBox.ItemTemplate>
        </ListBox>
        <Button Content="New" Click="NewButton_Pressed"/>
    </Grid>
</UserControl>

The working code behind is this:

  using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using System.Windows.Controls;

namespace WPFCentralOffice.UserControls
{
    public class Element : IEquatable<Element>
    {
        public int ID { get; set; }
        public string Caption { get; set; }

        public bool Equals(Element other)
        {
            return ID == other.ID;
        }

        public override string ToString()
        {
            return Caption;
        }
    }

    public class ComboBoxBindingSource : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public ComboBoxBindingSource(Element selectedElement, IEnumerable<Element> availableElements)
        {
            _selectedElement = selectedElement;
            AvailableElements = availableElements;
        }

        private Element _selectedElement;
        public Element SelectedElement
        {
            get { return _selectedElement; }
            set
            {
                _selectedElement = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("SelectedElement"));
                }
            }
        }

        private IEnumerable<Element> _availableElements;
        public IEnumerable<Element> AvailableElements
        {
            get { return _availableElements; }
            set
            {
                _availableElements = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("AvailableElements"));
                }
            }
        }
    }

    public partial class MultiSelectListUserControl : UserControl
    {
        public IEnumerable<Element> ChosenItems
        {
            get { return ComboBoxBindingSources.Select(x => x.SelectedElement); }
        }

        public ObservableCollection<Element> AllItems
        {
            get { return (ObservableCollection<Element>)GetValue(AllItemsProperty); }
            set { SetValue(AllItemsProperty, value); }
        }

        // ReSharper disable once InconsistentNaming
        public ObservableCollection<ComboBoxBindingSource> ComboBoxBindingSources
        {
            get { return (ObservableCollection<ComboBoxBindingSource>)GetValue(ComboBoxBindingSourcesProperty); }
            set { SetValue(ComboBoxBindingSourcesProperty, value); }
        }

        public static DependencyProperty AllItemsProperty = DependencyProperty.Register(
            "AllItems",
            typeof(ObservableCollection<Element>),
            typeof(MultiSelectListUserControl),
            new FrameworkPropertyMetadata(OnAllItemsChanged));

        private static void OnAllItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((MultiSelectListUserControl)d).RefreshAvailableItems();
        }

        public static DependencyProperty ComboBoxBindingSourcesProperty = DependencyProperty.Register(
            "ComboBoxBindingSources",
            typeof(ObservableCollection<ComboBoxBindingSource>),
            typeof(MultiSelectListUserControl));

        public void NewButton_Pressed(object sender, RoutedEventArgs e)
        {
            if (!AllItems.Any() || AllItems.Count == ComboBoxBindingSources.Count)
            {
                return;
            }

            var remainingItems = AllItems.Where(x => ChosenItems.All(y => x.ID != y.ID)).ToList();
            ComboBoxBindingSources.Add(new ComboBoxBindingSource(remainingItems.First(), remainingItems));
            RefreshAvailableItems();
        }

        public void ComboBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            RefreshAvailableItems();
        }

        private void RefreshAvailableItems()
        {
            if (ComboBoxBindingSources == null)
            {
                ComboBoxBindingSources = new ObservableCollection<ComboBoxBindingSource>();
            }
            foreach (var source in ComboBoxBindingSources)
            {
                var newAvailables =
                    AllItems.Where(
                        x => source.SelectedElement == x || ComboBoxBindingSources.All(y => y.SelectedElement != x));
                source.AvailableElements = newAvailables;
            }
        }

        public MultiSelectListUserControl()
        {
            InitializeComponent();
            SetValue(AllItemsProperty, new ObservableCollection<Element>());
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.