ComboBox设置选项与反显
效果如下:
初始化后根据数据源反显选项,根据操作修改、清空数据源
数据结构
internal class SettingWithComboBoxDemoViewModel : INotifyPropertyChanged
{
public ObservableCollection Fruits { get; set; }
private FruitViewModel selectFruit;
public FruitViewModel SelectFruit
{
get { return selectFruit; }
set
{
if (selectFruit != value)
{
selectFruit = value;
NotifyPropertyChanged(nameof(SelectFruit));
}
}
}
#region INotifyPropertyChanged Members
///
/// Need to implement this interface in order to get data binding
/// to work properly.
///
///
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
ui
后端
public partial class SettingWithComboBoxDemo : UserControl
{
SettingWithComboBoxDemoViewModel vm { get; set; }
public SettingWithComboBoxDemo()
{
InitializeComponent();
vm = new SettingWithComboBoxDemoViewModel();
vm.Fruits = new ObservableCollection();
vm.Fruits.Add(new FruitViewModel() { Id = 1, Name = "Apple" });
vm.Fruits.Add(new FruitViewModel() { Id = 2, Name = "Pear" });
vm.Fruits.Add(new FruitViewModel() { Id = 3, Name = "Banana" });
//设置选项,反显
vm.SelectFruit = vm.Fruits.FirstOrDefault(x => x.Id == 1);
DataContext = vm;
}
private void GetCurrentSelectItem_Click(object sender, System.Windows.RoutedEventArgs e)
{
if(vm.SelectFruit!=null)
MessageBox.Show($"{vm.SelectFruit.Name}");
else
MessageBox.Show($"None(没有选项)");
}
private void ResetSelectItem_Click(object sender, RoutedEventArgs e)
{
//清空
vm.SelectFruit = null;
}
}
示例代码
SettingWithComboBoxDemo