我有一个Commobox,它将基于选择更改将数据加载到数据网格中。关于Combobox选择的更改,我需要检查数据网格中的当前数据是否正确。如果不正确,我想取消ComboBox选择更改。
这是我的行为类
public class ComboBoxSelectionBehaviour : Behavior<ComboBox>
{
public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached(
"Source",
typeof(ViewModel),
typeof(ComboBoxSelectionBehaviour),
new PropertyMetadata(null));
public ViewModel Source
{
get { return (ViewModel)GetValue(SourceProperty); }
set { SetValue(SourceProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged; ;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
}
private void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var combo = sender as ComboBox;
if (Source != null)
{
// Suppress the event if errors exist
if (!Source.IsDataCorrect())
{
e.Handled = true;
}
}
}
}
即使在处理事件组合后,选定的项目也会更改。
请给出一些解决此问题的建议。
您可以只是做一个
myComboBox.SelectedIndex--
如果数据不正确?还是这会导致无限循环?