Toadums
Toadums

Reputation: 2812

Is there a BeforeCheck for WPF checkboxes?

Some of the checkboxes on my form should not be able to be checked/unchecked by users. Is there a way for me to cancel the event before the checbox's Check event is triggered?

in winForms it was easy, just

public void cb_BeforeChecked(object sender, EventArgs e){
    e.Handled = true;
}

but I cannot find anything like this in WPF...I figure you can probably do it, just need to do something fancy..

Thanks!

Upvotes: 1

Views: 328

Answers (5)

Schu
Schu

Reputation: 1164

You can have the check box disabled, and associate a style with the disabled check box, if the disabled look is a problem. As its already pointed in the previous posts, its good to have different looks for different states.

Upvotes: 1

Fredrik Hedblad
Fredrik Hedblad

Reputation: 84656

Only setting IsHitTestVisible="False" just takes care of the Mouse, the users can still use the KeyBoard to tab to the CheckBox and change the value.

You should set both IsHitTestVisible="False" and Focusable="False" to disable the KeyBoard as well

Upvotes: 1

Rachel
Rachel

Reputation: 132568

Why not just set IsEnabled="False"?

Upvotes: 2

Bahri Gungor
Bahri Gungor

Reputation: 2319

You can set IsHitTestVisible="False" to make it not respond to user clicks. Otherwise you can bind it to a command if viewmodel logic determines whether it is clickable.

<Grid>
    <CheckBox IsHitTestVisible="False" Content="I cannot be clicked at all"/>
<CheckBox Command="{Binding DoSomethingCommand}" Content="I can be clicked if DoSomethingCanExecute returns true."/>
</Grid>

In your DataContext (Viewmodel or otherwise):

    RelayCommand _DoSomethingCommand = null;

    public ICommand DoSomethingCommand
    {
        get
        {
            if (_DoSomethingCommand== null)
            {
                _DoSomethingCommand= new RelayCommand(
                    param => DoSomething(),
                    param => DoSomethingCanExecute
                    );
            }
            return _DoSomethingCommand;
        }
    }

    public bool DoSomethingCanExecute
    {
        get
        {
            return CheckboxShouldBeEnabled();
        }
    }

    public void DoSomething()
    {
        //Checkbox has been clicked
    }

Upvotes: 2

Philipp Schmid
Philipp Schmid

Reputation: 5828

This might be a bit of an overkill, but you could sub-class CheckBox and then override the OnClick() method.

Upvotes: 1

Related Questions