当前位置:网站首页>WPF combobox setting options and anti display

WPF combobox setting options and anti display

2022-06-21 22:34:00 zLulus

The effect is as follows :
After initialization, the options are inverted according to the data source , Modify according to operation 、 Clear data source

data structure

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( Get current options )" Click="GetCurrentSelectItem_Click"></Button>
    <Button Content="reset select item( Empty 、 Reset )" Click="ResetSelectItem_Click"></Button>
</StackPanel>

Back end

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" });
        // set an option , Reflexion 
        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( There are no options )");
    }

    private void ResetSelectItem_Click(object sender, RoutedEventArgs e)
    {
        // Empty 
        vm.SelectFruit = null;
    }
}

Sample code

SettingWithComboBoxDemo

原网站

版权声明
本文为[zLulus]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206212041018150.html