Disable WPF label accelerator key (text underscore is missing)

前端 未结 4 2047
逝去的感伤
逝去的感伤 2020-11-27 06:40

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.

Witho

相关标签:
4条回答
  • 2020-11-27 06:50

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

    0 讨论(0)
  • 2020-11-27 06:52

    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}" BasedOn="{StaticResource {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>
    
    0 讨论(0)
  • 2020-11-27 07:04

    Use a <TextBlock> ... </TextBlock> instead of <Label> ... </Label> to print the exact text, which is having underscores.

    0 讨论(0)
  • 2020-11-27 07:15

    Why not like this?

    public partial class LabelEx : Label
        {
            public bool PreventAccessKey { get; set; } = true;
    
            public LabelEx()
            {
                InitializeComponent();
            }
    
            public new object Content
            {
                get
                {
                    var content = base.Content;
                    if (content == null || !(content is string))
                        return content;
    
                    return PreventAccessKey ?
                        (content as string).Replace("__", "_") : content;
                }
                set
                {
                    if (value == null || !(value is string))
                    {
                        base.Content = value;
                        return;
                    }
    
                    base.Content = PreventAccessKey ?
                        (value as string).Replace("_", "__") : value;
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题