How do I disable dash + equals on a check box obje

2019-05-10 19:38发布

问题:

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

回答1:

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.



回答2:

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


回答3:

Try to override the keyboard shortcuts with empty commands:

<RadioButton>
        <KeyBinding Key="OemMinus" Command="{Binding EmptyCommand}"/>
</RadioButton>

And in your viewmodel:

// using System.windows.input

public Icommand EmptyCommand = ApplicationCommands.NotACommand;