Disabilita il tasto acceleratore dell'etichetta WPF (manca il carattere di sottolineatura del testo)
-
09-06-2019 - |
Domanda
Sto impostando il .Content
valore di un'etichetta in una stringa che contiene caratteri di sottolineatura;il primo carattere di sottolineatura viene interpretato come un tasto acceleratore.
Senza modificare la stringa sottostante (sostituendo all _
con __
), esiste un modo per disattivare l'acceleratore per le etichette?
Soluzione
Se utilizzi un TextBlock come contenuto dell'etichetta, il suo testo non assorbirà i caratteri di sottolineatura.
Altri suggerimenti
Potresti sovrascrivere la proprietà RecognizesAccessKey di ContentPresenter che si trova nel modello predefinito per l'etichetta.Per esempio:
<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>
Perché non così?
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;
}
}
}
Usare un <TextBlock> ... </TextBlock>
invece di <Label> ... </Label>
per stampare il testo esatto, che contiene caratteri di sottolineatura.