Question

How do I set the SelectedItem on a RibbonComboBox using MVVM pattern?

View

<ribbon:RibbonComboBox>
    <ribbon:RibbonGallery SelectedItem="{Binding Foobar, Mode=TwoWay}">
        <ribbon:RibbonGalleryCategory ItemsSource="{Binding Foobars}" DisplayMemberPath="FoobarID" />
    </ribbon:RibbonGallery>
</ribbon:RibbonComboBox>

ViewModel

// Selected Item
private Foobar _foobar { get; set; }

public Foobar Foobar
{
    get { return _foobar; }
    set
    {
        if (value == _foobar || value == null)
            return;

        _foobar = value;

        base.NotifyPropertyChanged("Foobar");
    }
}   

// Collection
private ObservableCollection<Foobar> _foobars = new ObservableCollection<Foobar>();

public ObservableCollection<Foobar> Foobars
{
    get
    {
        return _foobars;
    }
}

// Constructor
public FoobarViewModel(MyObject myObject)
{
    LoadFoobars();

    Foobar = myObject.Foobar;
}

// Method
private void LoadFoobars()
{
    foreach (var foobar in _localRepository.GetFoobars())
    {
        this._foobars.Add(foobar);
    }
}

Update

Removing IsEditable="True" does put "Namespace.Foobar" in the RibbonComboBox and changing SelectedItem and adding SelectedValuePath on the RibbonGallery does show the right value, but the RibbonComboBox has a red border, so I guess it is not validated (like comparing apples and pears).

<ribbon:RibbonComboBox>
    <ribbon:RibbonGallery SelectedItem="{Binding Foobar.FoobarID, Mode=TwoWay}" SelectedValuePath="DisplayMemberPath">
        <ribbon:RibbonGalleryCategory ItemsSource="{Binding Foobars}" DisplayMemberPath="FoobarID"/>
    </ribbon:RibbonGallery>
</ribbon:RibbonComboBox>
Was it helpful?

Solution

I solved it by changing the constructor.

// Constructor
public FoobarViewModel(MyObject myObject)
{
    LoadFoobars();

    Foobar = _repository.GetFoobar(myObject.FoobarID);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top