WPF listbox. Skip underscore symbols in strings

Use a double underscore string__string, since in WPF, the _ is the mnemonic character.

Even better, just solve this issue in xaml and create a collection in your view model (or code-behind).


The default template for the CheckBox contains a ContentPresenter whose RecognizesAccessKey is set to true. If the content is a string (which it is in your case), then the ContentPresenter creates an AccessText element to display the text. That element hides the underscore until the Alt key is pressed because it will treat it as a mnemonic. You can either retemplate the CheckBox such that its ContentPresenter's RecognizesAccessKey is false or better yet just provide a DataTemplate as the ContentTemplate which contains a TextBlock. If you're not sure if the content will be a string then you can set the ContentTemplateSelector and in code provide a DataTemplate which contains a TextBlock only if the item is a string. e.g.

<ListBox xmlns:sys="clr-namespace:System;assembly=mscorlib">
    <ListBox.Resources>
        <DataTemplate DataType="sys:String" x:Key="stringTemplate">
            <TextBlock Text="{Binding}" />
        </DataTemplate>
        <Style TargetType="CheckBox">
            <Setter Property="ContentTemplate" Value="{StaticResource stringTemplate}" />
        </Style>
    </ListBox.Resources>
    <ListBoxItem>
        <CheckBox Content="A_B" ContentTemplate="{StaticResource stringTemplate}"/>
        <!-- Or use the implicit style to set the ContentTemplate -->
        <CheckBox Content="A_B" />
    </ListBoxItem>
</ListBox>

You can add the text in a TextBlock and put that TextBlock inside your Chekbox, TextBlock does not support _ mnemonic characters. Here's what I mean, in xaml, but you can easily convert this to code:

<CheckBox IsChecked="True">
    <TextBlock>string_string</TextBlock>
</CheckBox>

Tags:

C#

Wpf