How to set SelectedItem on a RibbonComboBox using

2020-04-16 01:08发布

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>

1条回答
成全新的幸福
2楼-- · 2020-04-16 01:40

I solved it by changing the constructor.

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

    Foobar = _repository.GetFoobar(myObject.FoobarID);
}
查看更多
登录 后发表回答