2009-08-27 53 views
10

我在我的應用程序中使用TriState模式的複選框。這種模式的正常行爲似乎是循環介於空,錯,真。TriState複選框 - 如何更改狀態的順序

我想改變這種行爲,以便它在空,真,假之間循環。

這樣做的最好方法是什麼?

我嘗試添加一個類似的點擊處理程序:

void cb_Click(object sender, RoutedEventArgs e) 
{ 
    if (((CheckBox)e.Source).IsChecked.HasValue == false) 
    { 
     ((CheckBox)e.Source).IsChecked = true; 
     return; 
    } 

    if (((CheckBox)e.Source).IsChecked == true) 
    { 
     ((CheckBox)e.Source).IsChecked = false; 
     return; 
    } 

    if (((CheckBox)e.Source).IsChecked == false) 
    { 
     ((CheckBox)e.Source).IsChecked = null; 
     return; 
    } 

} 

但這似乎完全禁用的複選框。我很確定我錯過了一些顯而易見的東西。

回答

22

我猜的事件處理程序,默認的行爲只是相互抵消的作用,所以該複選框似乎禁用...

其實我最近不得不做同樣的事情。我不得不繼承CheckBox並覆蓋OnToggle

public class MyCheckBox : CheckBox 
{ 


    public bool InvertCheckStateOrder 
    { 
     get { return (bool)GetValue(InvertCheckStateOrderProperty); } 
     set { SetValue(InvertCheckStateOrderProperty, value); } 
    } 

    // Using a DependencyProperty as the backing store for InvertCheckStateOrder. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty InvertCheckStateOrderProperty = 
     DependencyProperty.Register("InvertCheckStateOrder", typeof(bool), typeof(MyCheckBox), new UIPropertyMetadata(false)); 

    protected override void OnToggle() 
    { 
     if (this.InvertCheckStateOrder) 
     { 
      if (this.IsChecked == true) 
      { 
       this.IsChecked = false; 
      } 
      else if (this.IsChecked == false) 
      { 
       this.IsChecked = this.IsThreeState ? null : (bool?)true; 
      } 
      else 
      { 
       this.IsChecked = true; 
      } 
     } 
     else 
     { 
      base.OnToggle(); 
     } 
    } 
} 
相關問題