c#,wpf 的mvvm模式下实现combobox数据绑定
结构:
1.在项目NuGet下安装MvvmLight
2.在ViewModelLocator.cs中删除不需要的引用,同时根据需要智能引用相应缺少的。
3.配置 App.config ,与下面的MainWindow.xaml中的DataContext对应起来
4.MainWindow.xaml 前台绑定 绑定ComboBox 的ItemSource , Text。
5. 后台逻辑就在 MainViewModel.cs中处理。
1 using GalaSoft.MvvmLight; 2 using System.Collections.Generic; 3 using System.Collections.ObjectModel; 4 5 namespace ComboboxExample.ViewModel 6 { 7 8 public class MainViewModel : ViewModelBase 9 { 10 #region Constructor 11 public MainViewModel() 12 { 13 this.GetFruitList(); 14 } 15 #endregion 16 17 #region Members 18 19 //Itemsource 20 private ObservableCollection<string> m_FriutList = new ObservableCollection<string>(); 21 public ObservableCollection<string> FriutList 22 { 23 get 24 { 25 return m_FriutList; 26 } 27 set 28 { 29 this.m_FriutList = value; 30 RaisePropertyChanged(nameof(FriutList)); 31 } 32 33 } 34 /// <summary> 35 /// 选择的文本或输入的文本 36 /// </summary> 37 private string m_SelectedText; 38 /// <summary> 39 /// 选择的文本或输入的文本 40 /// </summary> 41 public string SelectedText 42 { 43 get 44 { 45 return this.m_SelectedText; 46 } 47 set 48 { 49 this.m_SelectedText = value; 50 RaisePropertyChanged(nameof(SelectedText)); 51 } 52 } 53 54 #endregion 55 56 #region Command 57 58 #endregion 59 60 #region Methods 61 62 public void GetFruitList() 63 { 64 List<string> list = new List<string> 65 { 66 "apple", 67 "banana", 68 "watermellon", 69 "lemon", 70 "peach" 71 }; 72 73 list.ForEach(a => this.FriutList.Add(a)); 74 this.SelectedText = this.FriutList[0]; 75 } 76 77 #endregion 78 } 79 }
ps:平常Combobox不需要使用IsEditable= “True” 属性的话。获取选中的值可以使用 SelectedItem="{Binding SelectedItem,Mode=TwoWay}"来绑定。
wpf 可编辑的ComboBox绑定List数组和IsEditable属性绑定文本
原文:https://www.cnblogs.com/fimo/p/14692720.html