Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a CheckBox in my application that is using the TriState mode. The normal behavior for this mode seems to be cycling between null, false, true.

I'd like to change this behavior so that it cycles between null, true, false.

What's the best way to do this?

I've tried adding a click handler similar to this:

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;
    }

}

But this seems to disable the checkbox entirely. I'm pretty sure I'm missing something that should be obvious.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.9k views
Welcome To Ask or Share your Answers For Others

1 Answer

I guess the event handler and the default behavior are just cancelling each other's effects, so the checkbox seems disabled...

Actually I recently had to do the same thing. I had to inherit from CheckBox and override 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();
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share

548k questions

547k answers

4 comments

56.5k users

...