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

不更改底层字符串(通过替换所有 ___),有没有办法禁用标签的加速器?

有帮助吗?

解决方案

如果您使用 TextBlock 作为标签的内容,则其文本将不会吸收下划线。

其他提示

您可以覆盖标签默认模板中 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>

为什么不喜欢这样呢?

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

用一个 <TextBlock> ... </TextBlock>代替 <Label> ... </Label> 打印带有下划线的确切文本。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top