How to set/reset Three-state checkbox value in WPF

牧云@^-^@ 提交于 2019-12-04 05:23:14

Actually I got one better.

I found out that if I create a binding for IsThreeState, then change the value based on whether the value is set or not, then it works.

bool? _Value;
public bool? Value
{
    get { return _Value; }
    set
    {
        if (value == null)
        {
            IsThreeState = true;
        }
        else
        {
            IsThreeState = false;
        }
        _Value = value;

        NotifyPropertyChanged("Value");
    }
}

bool _IsThreeState = true;
public bool IsThreeState
{
    get { return _IsThreeState; }
    private set
    {
        _IsThreeState = value;
        NotifyPropertyChanged("IsThreeState");
    }
}

Now the checkbox will support threestate IFF the value is set to null externally. If the value is true or false, the user won't be able to set it to null.

Rafael

I found a simple way:

Adjust the event click of three state check box, and check if its value is null. If does change it to false. Like this:

        private void cbAllFeatures_Click(object sender, RoutedEventArgs e)
        {
            if (cbAllFeatures.IsChecked != null) return;

            cbAllFeatures.IsChecked = false;
        }

I hope you enjoy it.

This is what worked for me. I created a new FTThreeStateCheckBox (subclassed from CheckBox), overrode the IsCheckedProperty metadata so I could watch for changes in the value, then if it was null, I set IsThreeState and IsChecked to false.

static FTThreeStateCheckBox()
{
    IsCheckedProperty.OverrideMetadata(typeof(FTThreeStateCheckBox), new FrameworkPropertyMetadata(null, IsCheckedChanged));          
}


public static void IsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    if ((d as FTThreeStateCheckBox).IsChecked == null)
    {
        (d as FTThreeStateCheckBox).IsThreeState = false;
        (d as FTThreeStateCheckBox).IsChecked = false;
    }            
}

for people who want to achieve this

  • user can switch checkbox in the view only to true or false. Not to undefined!
  • code in ViewModel should be able to switch checkbox to undefined

just do this:

  • add checkbox to view but DONT set IsThreeState=true
  • bind IsChecked to a bool? (nullable bool) property in the ViewModel

You can now set it to null in the ViewModel while the user cannot do it in the View.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!