ComboBox设置选项与反显

效果如下:
初始化后根据数据源反显选项,根据操作修改、清空数据源

数据结构

internal class SettingWithComboBoxDemoViewModel : INotifyPropertyChanged
{
    public ObservableCollection<FruitViewModel> Fruits { get; set; }

    private FruitViewModel selectFruit;
    public FruitViewModel SelectFruit
    {
        get { return selectFruit; }
        set
        {
            if (selectFruit != value)
            {
                selectFruit = value;
                NotifyPropertyChanged(nameof(SelectFruit));
            }
        }
    }

    #region INotifyPropertyChanged Members

    /// <summary>
    /// Need to implement this interface in order to get data binding
    /// to work properly.
    /// </summary>
    /// <param name="propertyName"></param>
    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    #endregion
}

ui

<StackPanel Orientation="Vertical">
    <ComboBox ItemsSource="{Binding Fruits}" DisplayMemberPath="Name" SelectedItem="{Binding SelectFruit,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></ComboBox>
    <Button Content="get current select item(获得当前选项)" Click="GetCurrentSelectItem_Click"></Button>
    <Button Content="reset select item(清空、重置)" Click="ResetSelectItem_Click"></Button>
</StackPanel>

后端

public partial class SettingWithComboBoxDemo : UserControl
{
    SettingWithComboBoxDemoViewModel vm { get; set; }
    public SettingWithComboBoxDemo()
    {
        InitializeComponent();

        vm = new SettingWithComboBoxDemoViewModel();
        vm.Fruits = new ObservableCollection<FruitViewModel>();
        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

学习技术最好的文档就是官方文档,没有之一。
还有学习资料Microsoft LearnCSharp LearnMy Note
如果,你认为阅读这篇博客让你有些收获,不妨点击一下右下角的推荐按钮。
如果,你希望更容易地发现我的新博客,不妨点击一下关注

原文地址:https://www.cnblogs.com/Lulus/p/15739655.html