Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

wpf - TriState Checkbox - how to change the order of the states

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...