locked
Why does the IsChecked property not give a compile error if assigned a bool value?

    General discussion

  • For Info:

    I just wasted about 2 hours before solving a strange effect with multiple CheckBox's in my UI.

    The problem code:

    if (setCheckBoxToClicked)
    {
        //This gives no compile/warning message but will
        //not have the effect you intend!!
        _theView->IsChecked = true;
    }
    else
    {
        //This gives no compile/warning message but will
        //not have the effect you intend!!
        _theView->IsChecked = false;
    }
    
    ...
    
    //Also, dont do this:
    if (_theView->IsChecked)
    {
        //Process IsChecked true
    }
    else
    {
        //Process IsChecked false
    }
    


    The fixed code was:

    if (setCheckBoxToClicked)
    {
        //NB: IsChecked is of type 'IReference<bool>' rather than just 'bool'
        //because a CheckBox can have 3 states (true,false,null) and a
        //C++ 'bool' only has two!.
        Platform::Object^ pvBool = Windows::Foundation::PropertyValue::CreateBoolean(true);
        Platform::IBox<bool>^ iboxBool = dynamic_cast<Platform::IBox<bool>^>(pvBool);
        _theView->IsChecked = iboxBool;
    }
    else
    {
        Platform::Object^ pvBool = Windows::Foundation::PropertyValue::CreateBoolean(false); 
        Platform::IBox<bool>^ iboxBool = dynamic_cast<Platform::IBox<bool>^>(pvBool);
        _theView->IsChecked = iboxBool;
    }
    
    ...
    
    //To query the IsChecked property use:
    Platform::IBox<bool>^ iboxBool = _theView->IsChecked;
    if (iboxBool->Value)
    {
        //Process IsChecked true
    }
    else
    {
        //Process IsChecked false
    }
    

    This was my fault for not reading the documentation 'carefully enough' and assuming that the 'IsChecked' would be of type 'bool' (as all the other 'Is' properties that I have used so far have been).

    It would be helpful if the compiler generated an error or a warning in this case?


    Thursday, April 18, 2013 10:07 AM

All replies