在我的 WPF 应用程序中,我有多个接收 json 文本的 Avalon 文本框。对于语法突出显示,我使用官方 .xshd 文件 (https://github.com/icsharpcode/AvalonEdit/blob/master/ICSharpCode.AvalonEdit/Highlighting/Resources/Json.xshd)
问题:当我在 Avalon 文本框中输入“some, text”时,当我使用双击鼠标(或使用键盘快捷键进行选择)选择逗号字符时,它会自动显示反斜杠 (\)。同样,如果我们选择任何其他特殊字符(例如 { 或 }),它会显示 __。
很奇怪吧?
由于我的 avalon 文本框是在多个窗口中使用的,所以我将 avalon 文本编辑器集中在一个类中,并在需要的地方在 xaml 文件中实例化其对象。
下面是通过将 Text 属性作为依赖属性来实现的常见类实现,以便我可以将 text 属性与我的 viewmodel 属性绑定
public class CustomizedPrettyJSONTextBox : TextEditor, INotifyPropertyChanged
{
public CustomizedPrettyJSONTextBox()
{
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("mynamespace.JSONSyntaxColoringRule.xshd"))
{
if (stream != null)
{
using (XmlReader reader = new XmlTextReader(stream))
{
IHighlightingDefinition highlightingDefinition = HighlightingLoader.Load(reader, HighlightingManager.Instance);
((TextEditor)this).SyntaxHighlighting = highlightingDefinition;
}
}
}
}
public static DependencyProperty TextProperty =
DependencyProperty.Register("Text",
typeof(string), typeof(CustomizedPrettyJSONTextBox),
new PropertyMetadata((obj, args) =>
{
CustomizedPrettyJSONTextBox target = (CustomizedPrettyJSONTextBox)obj;
if (target.Text != (string)args.NewValue)
target.Text = (string)args.NewValue;
})
);
public string Text
{
get { return base.Text; }
set { base.Text = Helpers.GetProperJSONFormat(value); }
}
protected override void OnTextChanged(EventArgs e)
{
SetCurrentValue(TextProperty, base.Text);
RaisePropertyChanged(TextProperty.Name);
base.OnTextChanged(e);
}
public event PropertyChangedEventHandler? PropertyChanged;
public void RaisePropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
下面是我如何在 xaml 文件中使用此类对象的一个示例
<mynamespace:CustomizedPrettyJSONTextBox x:Name="avalonJSONTextBox" Margin="10" Grid.Row="2"
Style="{StaticResource CustomJSONTextBoxStyle}" >
<Binding Path="MyViewModelProperty" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<commonItems:JSONValidator />
</Binding.ValidationRules>
</Binding>
</mynamespace:CustomizedPrettyJSONTextBox>
请帮助我如何避免这种行为。
尝试设置
editor.TextArea.SelectionCornerRadius = 0;
AvalonEdit 使用的圆形选择不适用于非常细的字符,从而导致奇怪的视觉效果。