如何使用MVVM在RibbonComboBox上设置SelectedItem? [英] How to set SelectedItem on a RibbonComboBox using MVVM?

查看:183
本文介绍了如何使用MVVM在RibbonComboBox上设置SelectedItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用MVVM模式在RibbonComboBox上设置SelectedItem?

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

查看

<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);
    }
}

更新

删除IsEditable="True"确实会将RibbonComboBox中,并更改SelectedItem并在RibbonGallery上添加SelectedValuePath确实显示正确的值,但是RibbonComboBox有红色边框,所以我想它没有经过验证(例如比较苹果和梨).

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>

推荐答案

我通过更改构造函数解决了该问题.

I solved it by changing the constructor.

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

    Foobar = _repository.GetFoobar(myObject.FoobarID);
}

这篇关于如何使用MVVM在RibbonComboBox上设置SelectedItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆