如何设置的SelectedItem使用MVVM一个RibbonComboBox?(How to se

2019-07-28 21:57发布

我如何设置SelectedItemRibbonComboBox使用MVVM模式?

视图

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

视图模型

// 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"中没有把“Namespace.Foobar” RibbonComboBox和改变SelectedItem和添加SelectedValuePathRibbonGallery确实显示正确的价值,但RibbonComboBox有一个红色的边框,所以我想它没有被确认(如比较苹果和梨)。

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

Answer 1:

我通过改变构造解决它。

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

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


文章来源: How to set SelectedItem on a RibbonComboBox using MVVM?