Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WPF

ComboBox ObservableCollection Overkill

4.92/5 (5 votes)
6 Dec 2013CPOL1 min read 19.4K  
RibbonComboBox in MVVM/WPF: the easiest way

Introduction

When you implement a RibbonComboBox in .NET 4.5, WPF (or a ComboBox in general) and you want to apply MVVM, you find tons of examples using an ObservableCollection for this. But in how many cases do the values selectable in your (Ribbon)ComboBox really change during runtime of the program? If they do not, take it easy: a simple array instead of the ObservableCollection is enough.

Using the Code

Look at this simple property in your ViewModel:

C#
public int[] SelectableValues { get { return new int[] { 20, 30, 40, 45, 48 }; } }

This is the corresponding XAML:

XML
<RibbonComboBox SelectionBoxWidth="30" 
IsEditable="False" IsReadOnly="False">
    <RibbonGallery SelectedValue="{Binding ActualValue}">
        <RibbonGalleryCategory ItemsSource="{Binding SelectableValues}" />
    </RibbonGallery>
</RibbonComboBox> 

And here we have the actually selected value (again in the ViewModel, I suggest):

C#
private int _actualValue;
public int ActualValue
{
   get { return _actualValue; }
   set
   {
      if (_actualValue == value) return;
      _ actualValue = value;
      RaisePropertyChanged("ActualValue");
   }
}

That's it. No ObservableCollection. Because there is nothing to observe. Only the selected value changes, but the collection of values itself does not change - if it really does not change, of course.

Points of Interest

The internet is full of examples addressing this topic. But I think these examples are too complicated when the list of selectable values does not change.

You can also use string[] and even MyClass[] as array for fixed values (instead of the ObservableCollection). In case of a class, simply override its ToString()-method and there return the specific property of your class you want to see in the (Ribbon)ComboBox.

History

  • 6.12.2013: First posted

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)