2008-09-02 60 views
55

我將標籤的.Content值設置爲包含下劃線的字符串;第一個下劃線被解釋爲加速鍵。禁用WPF標籤加速鍵(缺少文本下劃線)

沒有改變底層字符串(通過替換所有___),有沒有辦法來禁用標籤的加速器?

+1

是否有你想使用標籤而不是TextBlock的原因? – 2008-09-02 21:36:34

+1

是的 - `Label`處理加速器的功能遠不止於此。也適用於不能被「TextBlock」替代的其他控件(例如`GroupBox`)。 – GraemeF 2010-03-01 10:08:25

+0

這對這個主題很有幫助: http://stackoverflow.com/questions/10452462/make-a-hotkey-to-focus-a-textbox-in-wpf – 2016-01-21 07:52:58

回答

76

如果您使用TextBlock作爲標籤的內容,其文本將不會吸收下劃線。

26

您可以覆蓋默認模板中標籤的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> 
+0

剛試過這個,實際上並不起作用。也許它會刪除訪問鍵綁定,但它不會阻止刪除下劃線。 – xanadont 2009-05-14 04:23:47

1

使用<"Text Block">"<"/Text Block"> 而不是<"label"><"/label">來打印具有下劃線的確切文本。

0

爲什麼不能這樣?

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