WPF ComboBox SelectedItem - change to previous value

前端 未结 4 1049
Happy的楠姐
Happy的楠姐 2020-12-30 00:13

I have a ComboBox that has the SelectedItem bound to the ViewModel.



        
4条回答
  •  粉色の甜心
    2020-12-30 01:01

    My way of doing it is to let the change go through and perform validation in a lambda that is BeginInvoked in the Dispatcher.

        public ObservableCollection Items { get; set; }
        private string _selectedItem;
        private string _oldSelectedItem;
        public string SelectedItem
        {
            get { return _selectedItem; }
            set {
                _oldSelectedItem = _selectedItem;
                _selectedItem = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("SelectedItem"));
                }
                Dispatcher.BeginInvoke(new Action(Validate));                
            }
        }
    
        private void Validate()
        {            
            if (SelectedItem == "Item 5")
            {
                if (MessageBox.Show("Keep 5?", "Title", MessageBoxButton.YesNo) == MessageBoxResult.No)
                {
                    SelectedItem = _oldSelectedItem;
                }
            }
        }
    

    or in your ViewModel:

       Synchronization.Current.Post(new SendOrPostCallback(Validate), null);
    

提交回复
热议问题