Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable dash + equals on a check box object in xaml?

I have a datatemplate xaml that currently looks like this for a report screen

   <CheckBox>
        <StackPanel>
            <TextBlock Text="{Binding Path=DisplayName}" FontWeight="Bold" Margin="0 0 0 5" />
            <RadioButton Content="All Pages" IsChecked="{Binding Path=AllPages}" Margin="0 0 0 5" />
            <RadioButton>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Pages: " Margin="0 3 5 0" />
                    <TextBox Width="130" Text="{Binding Path=SelectedValue}" />
                </StackPanel>
            </RadioButton>
        </StackPanel>
  </CheckBox>

I want to know, how I can disable the default checkbox behavior that uses '-' and '=' as chek and uncheck.

I want to allow the user in that textbox to type in '1-5, 6, 7' for page ranges, but cannot do so because '-' is checking and unchecking the box

EDIT: I would like to maintain the spacebar functionality of checking + unchecking the checkbox. For whatever reason, if I am in the textbox and I type space, it doesn't trigger the toggle event, but the '-' and '=' do.

EDIT2: Ideally looking for a xaml fix since I am trying to maintain an MVVM architecture and would prefer not to have code behind

like image 432
asdasda sdasdasdasd Avatar asked Oct 27 '25 14:10

asdasda sdasdasdasd


2 Answers

CheckBox.OnKeyDown is the culprit (see http://msdn.microsoft.com/en-us/library/system.windows.controls.checkbox.onkeydown.aspx). I solved this by making a custom CheckBox class that overrides OnKeyDown and does nothing. The VB solution would look like:

Public Class IgnoreKeyboardCheckBox
    Inherits CheckBox

    Protected Overrides Sub OnKeyDown(e As System.Windows.Input.KeyEventArgs)
        If e.Key = Key.Space Then
            MyBase.OnKeyDown(e)
        End If
    End Sub
End Class

You can use this class instead of CheckBox whenever you need the checkbox to ignore keyboard inputs.

like image 105
LAE Avatar answered Oct 29 '25 04:10

LAE


As can be seen here CheckBox.cs source code in C# .NET, for 2-state checkboxes there is custom behaviour for Key.Add, Key.Subtract, Key.OemPlus, Key.OemMinus.

(Programmatically) adding commands didn't work for me. Overriding in a subclass did:

protected override void OnKeyDown(KeyEventArgs e)
{
  // Non ThreeState Checkboxes natively handle certain keys.
  if (SuppressNativeKeyDownBehaviour(e.Key))
    return;

  base.OnKeyDown(e);
}

private bool SuppressNativeKeyDownBehaviour(Key key)
{
  switch (key)
  {
    case Key.Add:
    case Key.Subtract:
    case Key.OemPlus:
    case Key.OemMinus:
      return true;
    default:
      return false;
  }
}
like image 34
EricG Avatar answered Oct 29 '25 02:10

EricG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!