问题
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:
I solved it by changing the constructor.
// Constructor
public FoobarViewModel(MyObject myObject)
{
LoadFoobars();
Foobar = _repository.GetFoobar(myObject.FoobarID);
}
来源:https://stackoverflow.com/questions/10107992/how-to-set-selecteditem-on-a-ribboncombobox-using-mvvm