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
:
public int[] SelectableValues { get { return new int[] { 20, 30, 40, 45, 48 }; } }
This is the corresponding XAML:
<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):
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