Friday, February 4, 2011

Disable WPF label accelerator key (text underscore is missing)

I am setting the .Content value of a Label to a string that contains underscores; the first underscore is being interpreted as an accelerator key.

Without changing the underlying string (by replacing all _ with __), is there a way to disable the accelerator for Labels?

  • Is there a reason you want to use a Label as opposed to a TextBlock?

    GraemeF : Yes - `Label` does a lot more than handle the accelerators. Also applies to other controls (e.g. `GroupBox`) that can't be replaced by a `TextBlock`.
  • You could override the RecognizesAccessKey property of the ContentPresenter that is in the default template for the label. For example:

    <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Grid>
        <Grid.Resources>
          <Style x:Key="{x:Type Label}" TargetType="Label">
            <Setter Property="Template">
              <Setter.Value>
                <ControlTemplate TargetType="Label">
                  <Border>
                    <ContentPresenter
                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                      RecognizesAccessKey="False" />
                  </Border>
                </ControlTemplate>
              </Setter.Value>
            </Setter>
          </Style>
        </Grid.Resources>
        <Label>_This is a test</Label>
      </Grid>
    </Page>
    
    xanadont : Just tried this, doesn't work, actually. Perhaps it does remove access-key binding, but it doesn't prevent the underscore from being removed.
    dpp : Just copied the code into Kaxaml and worked. Did you try as is or change it at all?
    Simpzon : Works on my machine, too.
    Anders Rune Jensen : Works for me, but changes the way a label looks :(
    From dpp
  • Although Label is heavier, it does support nice alignment features which TextBlock does not. For instance, TextBlock does not have an analog to VerticalContentAlignment.

    From micahtan
  • If you use a TextBlock as the Content of the Label, its Text will not absorb underscores.

    RQDQ : I just used this approach in my app and it worked like a champ.
    From yota

0 comments:

Post a Comment