ComboBox SelectedIndex MVVM WPF

Har*_*raf 1 c# wpf xaml combobox mvvm

我有一个ComboBox绑定到一个ObservableCollection,tbPublications其中应该填充它.然后我从DataGrid中选择一行,它触发另一个我在其中插入新记录的Create表单tbPublications,一切都很好.

当我关闭所述创建表单并返回到我的ComboBox表单时,我正在清理并重新读取我的一个新项目ObservableCollection,将用户返回到他们刚刚创建的项目.然后ComboBox显示我新填充的集合中的一个项目,一切都很好.

我的问题是,在返回我的ComboBox表单时,新的出版物未设置为ComboBox显示中的选定项目,用户必须单击ComboBox然后选择该项目.

我无法SelectedIndex = "0"在我的视图中使用XAML,因为我想ObservableCollection在页面加载时在我的ComboBox中显示整个内容.

是否有任何方法可以在ViewModel中使用方法来解决这个问题,例如...

      private void SetSelectedIndex()
      {
        if (MyObservableCollection.Count == 1)
        {
            //Set selected indexer to "0";
        }
      }
Run Code Online (Sandbox Code Playgroud)

找到了解决方案,不确定它是否是最干净的"MVVM"解决方案......

在我的ObservableCollection中读取后,我调用了这个方法:

 if (_ModelPublicationsObservableList.Count == 1)
                {
                    SelectedPublication = _ModelPublication;
                    SetSelectedIndex();
                }
Run Code Online (Sandbox Code Playgroud)

这是获取当前主窗口并设置SelectedIndex的方法:

 private void SetSelectedIndex()
    {
        ArticlesDataGridWindow singleOrDefault = (ComboBoxWindow)Application.Current.Windows.OfType<ComboBoxWindow>().SingleOrDefault(x => x.IsLoaded);
        singleOrDefault.comboBox1.SelectedIndex = 0;        
    }
Run Code Online (Sandbox Code Playgroud)

Ram*_*kar 8

您是否考虑使用组合框的SelectedItem属性?您可以绑定组合框的选定项属性以获取或设置所选项.

XAML

<ComboBox ItemsSource="{Binding Path=Publications}" SelectedItem="{Binding Path=SelectedPublication, Mode=TwoWay}" />
Run Code Online (Sandbox Code Playgroud)

视图模型

public class ItemListViewModel
{
    public ObservableCollection<Publication> Publications {get; set;}

    private Publication _selectedPublication;
    public Publication SelectedPublication 
    {
        get { return _selectedPublication; }
        set
        {
            if (_selectedPublication== value) return;
            _selectedPublication= value;
            RaisePropertyChanged("SelectedPublication");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果要从View模型中设置所选项目,可以将SelectedPublication属性设置为-

SelectedPublication = Publications[0];
Run Code Online (Sandbox Code Playgroud)

或者,您可以在Publications集合中找到所需的项目,并将其分配给SelectedPublication 属性.

  • +1.这几乎总是要走的路,除非概念"选择值"是`ComboBox`中的*项的*属性(与项目本身相对),在这种情况下,可以使用`SelectedValue`和`SelectedValuePath`.在跟随MVVM时,几乎没有理由使用`SelectedIndex`. (2认同)