如果选择无效,在事件处理程序中进行验证SelectionChanged
允许您取消逻辑,但我不知道取消事件或项目选择的简单方法。
我的解决方案是对 WPF 组合框进行子类化并为SelectionChanged
事件添加一个内部处理程序。每当事件触发时,我的私有内部处理程序都会引发自定义SelectionChanging
事件。
如果在Cancel
相应的 上设置了属性SelectionChangingEventArgs
,则不会引发事件并且将SelectedIndex
恢复为之前的值。否则SelectionChanged
会引发一个新的遮蔽基本事件的事件。希望这会有所帮助!
SelectionChanging 事件的 EventArgs 和处理程序委托:
public class SelectionChangingEventArgs : RoutedEventArgs
{
public bool Cancel { get; set; }
}
public delegate void
SelectionChangingEventHandler(Object sender, SelectionChangingEventArgs e);
改变组合框类实现:
public class ChangingComboBox : ComboBox
{
private int _index;
private int _lastIndex;
private bool _suppress;
public event SelectionChangingEventHandler SelectionChanging;
public new event SelectionChangedEventHandler SelectionChanged;
public ChangingComboBox()
{
_index = -1;
_lastIndex = 0;
_suppress = false;
base.SelectionChanged += InternalSelectionChanged;
}
private void InternalSelectionChanged(Object s, SelectionChangedEventArgs e)
{
var args = new SelectionChangingEventArgs();
OnSelectionChanging(args);
if(args.Cancel)
{
return;
}
OnSelectionChanged(e);
}
public new void OnSelectionChanged(SelectionChangedEventArgs e)
{
if (_suppress) return;
// The selection has changed, so _index must be updated
_index = SelectedIndex;
if (SelectionChanged != null)
{
SelectionChanged(this, e);
}
}
public void OnSelectionChanging(SelectionChangingEventArgs e)
{
if (_suppress) return;
// Recall the last SelectedIndex before raising SelectionChanging
_lastIndex = (_index >= 0) ? _index : SelectedIndex;
if(SelectionChanging == null) return;
// Invoke user event handler and revert to last
// selected index if user cancels the change
SelectionChanging(this, e);
if (e.Cancel)
{
_suppress = true;
SelectedIndex = _lastIndex;
_suppress = false;
}
}
}