繁体   English   中英

ComboBox SelectedIndex MVVM WPF

[英]ComboBox SelectedIndex MVVM WPF

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

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

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

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

有什么方法可以在ViewModel中使用方法来解决此问题,例如。

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

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

阅读我的ObservableCollection之后,我将调用此方法:

 if (_ModelPublicationsObservableList.Count == 1)
                {
                    SelectedPublication = _ModelPublication;
                    SetSelectedIndex();
                }

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

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

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

XAML

<ComboBox ItemsSource="{Binding Path=Publications}" SelectedItem="{Binding Path=SelectedPublication, Mode=TwoWay}" />

视图模型

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

如果要设置View模型中的选定项,则可以将SelectedPublication属性设置为-

SelectedPublication = Publications[0];

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

UpdateSourceTrigger = PropertyChanged添加到您的绑定中。

SelectedItem={Binding Path=SelectedPublication, Mode=TwoWay}, UpdateSourceTrigger=PropertyChanged}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM