WPF 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

posted @ 2021-12-28 10:38  Lulus  阅读(459)  评论(0编辑  收藏  举报