代码之家  ›  专栏  ›  技术社区  ›  Richard Morgan

禁用WPF标签快捷键(缺少文本下划线)

  •  56
  • Richard Morgan  · 技术社区  · 17 年前

    我正在设置 .Content 包含下划线的字符串的标签值;第一个下划线被解释为快捷键。

    不更改基础字符串(通过全部替换 _ 具有 __ )是否有方法禁用标签加速器?

    4 回复  |  直到 7 年前
        1
  •  77
  •   yota    15 年前

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

        2
  •  27
  •   gav    14 年前

    可以重写标签默认模板中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>
    
        3
  •  1
  •   Martin Backasch    7 年前

    使用A <TextBlock> ... </TextBlock> 而不是 <Label> ... </Label> 打印带有下划线的准确文本。

        4
  •  0
  •   user6416335    8 年前

    为什么不这样?

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