禁用WPF标签加速键(缺少文本下划线)

时间:2020-03-05 18:46:46  来源:igfitidea点击:

我将Label的.Content值设置为包含下划线的字符串;第一个下划线被解释为加速键。

在不更改基础字符串的情况下(通过将所有的_替换为__),是否可以禁用标签加速器?

解决方案

回答

我们可以覆盖标签默认模板中的ContentPresenter的RecognizesAccessKey属性。例如:

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

回答

如果将TextBlock用作标签的内容,则其Text不会吸收下划线。