WPF列表框.在字符串中跳过下划线符号

ill*_*ant 24 c# wpf

我有一些WPF ListBox,它动态填充项目.像这样的东西:

ListBox.Items.Add
(new ListBoxItem { Content = new CheckBox { IsChecked = true, Content = "string_string"} );
Run Code Online (Sandbox Code Playgroud)

问题出在复选框内容上.它在GUI上显示为"stringstring"...如何逃避"_"符号?(我动态获取字符串)

And*_*ana 28

您可以在TextBlock中添加文本并将该TextBlock放入Chekbox中,TextBlock不支持_助记符.这就是我的意思,在xaml中,但您可以轻松地将其转换为代码:

<CheckBox IsChecked="True">
    <TextBlock>string_string</TextBlock>
</CheckBox>
Run Code Online (Sandbox Code Playgroud)

  • 使用`<ListBox.Resources> <Style TargetType ="ContentPresenter"> <Setter Property ="RecognizesAccessKey"Value ="False"/> </ Style> </ListBox.Resources>`没有帮助,顺便说一下.. . (2认同)

小智 14

CheckBox的默认模板包含一个ContentPresenter,其RecognizesAccessKey设置为true.如果内容是字符串(在您的情况下),则ContentPresenter会创建一个AccessText元素来显示文本.该元素隐藏下划线直到按下Alt键,因为它会将其视为助记符.您可以重新尝试CheckBox,使其ContentPresenter的RecognizesAccessKey为false或更好,但只提供DataTemplate作为包含TextBlock的ContentTemplate.如果您不确定内容是否为字符串,则可以设置ContentTemplateSelector,并在代码中提供仅在项目为字符串时包含TextBlock的DataTemplate.例如

<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>
Run Code Online (Sandbox Code Playgroud)


Gee*_*rik 7

使用双下划线string__string,因为在WPF中,_是助记符.

更好的是,只需在xaml中解决此问题,并在视图模型(或代码隐藏)中创建一个集合.

  • 然后,如果我想要在某些代码中获取字符串,我必须记住再做一次替换...认为texblocks是这种方式最优雅的解决方案 (2认同)
  • 是的,文本块方法更有效. (2认同)