在WPF文本框中显示特殊字符

问题描述 投票:1回答:1

我有一个类似[VIP]的字符串,但文本框仅将其显示为[VIP]。如何在浏览器中像正方形一样显示这些特殊字符?试图设置多个字体系列(<Setter Property="FontFamily" Value="Arial, Symbol"/>),但是它不起作用。我不想使用richtextbox,因为它大大增加了窗口渲染时间。

upd:嗯,stackoverflow文本渲染器也吃了这个字符,所以字符串是"\u0001[\u0004VIP\u0001] "

c# wpf xaml textbox wpf-controls
1个回答
0
投票

希望我能很好地理解你的问题。

将以下附加属性添加到您的项目中。它可以将“ [”字符转换为“ \ u0001”。

class CharacterConvertBehavior : DependencyObject
{
    public static bool GetConvertEnable(DependencyObject obj)
    {
        return (bool)obj.GetValue(ConvertEnableProperty);
    }

    public static void SetConvertEnable(DependencyObject obj, bool value)
    {
        obj.SetValue(ConvertEnableProperty, value);
    }

    // Using a DependencyProperty as the backing store for ConvertEnable.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty ConvertEnableProperty =
        DependencyProperty.RegisterAttached("ConvertEnable", typeof(bool), typeof(CharacterConvertBehavior), new PropertyMetadata(ConvertEnableChanged));


    private static void ConvertEnableChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;

        if ((bool)e.NewValue == true)
            textBox.PreviewKeyDown += TextBox_ConvertHandler;
        else
            textBox.PreviewKeyDown -= TextBox_ConvertHandler;
    }


    #region Convert Handler
    private static void TextBox_ConvertHandler(object sender, KeyEventArgs e)
    {
        var textBox = sender as TextBox;

        if (e.Key == Key.Oem4)  // "["
        {
            string convertString = "\\u0001";
            TextCompositionManager.StartComposition(new TextComposition(InputManager.Current, textBox, convertString));

            e.Handled = true;
        }
    }
    #endregion
}

以这种方式,您可以添加所需的功能。

上面的代码可以在主项目中使用,如下所示。

<Window x:Class="StackOverFlowAnswers.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:attached="clr-namespace:Parse.WpfControls.AttachedProperties"
        xmlns:local="clr-namespace:StackOverFlowAnswers"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="ConvertableTextBox" TargetType="TextBox">
            <Setter Property="attached:CharacterConvertBehavior.ConvertEnable" Value="True"/>
        </Style>
    </Window.Resources>

    <Grid>
        <TextBox Style="{StaticResource ConvertableTextBox}"/>
    </Grid>
</Window>
© www.soinside.com 2019 - 2024. All rights reserved.