2016-06-21 90 views
0

我有一个组合框将根据选择更改加载数据网格中的数据。 在更改组合框选择时,我需要检查数据网格中的当前数据是否正确。如果不正确,我想取消组合框选择更改。取消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; 
      } 
     } 
    } 

} 

即使处理事件组合框中选定的项目得到改变后,我的行为类。

请给出一些建议来解决这个问题。

+0

我建议在属性发生变化时在ViewModel上处理它。 – tgpdyk

回答

0

你能不能简单地只是做一个
myComboBox.SelectedIndex--

如果数据是不正确的?或者这会导致无限循环?

+0

是的,它会创建无限循环。所以我使用了previewmousedown和previewkeydown事件来处理这种情况。我知道它不干净,但仍然有效。 – Peekay