2016-06-21 29 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