WPF ラベル アクセラレータ キーを無効にする (テキストのアンダースコアが欠落しています)

StackOverflow https://stackoverflow.com/questions/40733

  •  09-06-2019
  •  | 
  •  

質問

を設定しています .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