WPF - MVVM: ComboBox value after SelectionChanged

前端 未结 2 636
轮回少年
轮回少年 2021-02-06 02:47

I am new to C# and MVVM, and I\'ve spent all day trying to get the value of a ComboBox to my ViewModel on SelectionChanged. I have managed to figure it

相关标签:
2条回答
  • 2021-02-06 03:27

    Why not do it the simpler way

    <ComboBox MaxHeight="25" 
              ItemsSource="{Binding Source}" 
              SelectedItem="{Binding TheSelectedItem, Mode=TwoWay}" />
    

    In your ViewModel declare the combo box items and use a property "Source" to return it to the view

    List<string> _source = new List<string>{"Item 1", "Item 2", "Item 3"};
    public List<string> Source 
    { 
        get { return _source; } 
    }
    

    Then define one property which holds the selected item

    string _theSelectedItem = null;
    public string TheSelectedItem 
    { 
        get { return _theSelectedItem; } 
        set { _theSelectedItem = value; } // NotifyPropertyChanged
    }
    

    Also don't forget to implement the INotifyPropertyChanged interface while setting the _source

    0 讨论(0)
  • 2021-02-06 03:37

    If you just want to get notified when your current item changes, why not use tools that are already part of WPF instead of all these dependencies.

    First get the underlying view to your collection and use the CurrentChanged event on it.

    ComboBoxList = new ObservableCollection<string>();
    var view = CollectionViewSource.GetDefaultView(ComboBoxList);
    view.MoveCurrentTo(ComboBoxList[0]);
    view.CurrentChanged += new EventHandler(ComboBoxCurrentChanged);
    

    In your xaml you just bind your collection and set IsSynchronizedWithCurrentItem to true.

    <ComboBox IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding ComboBoxList}"/>
    
    0 讨论(0)
提交回复
热议问题