【发布时间】:2023-03-04 09:55:02
【问题描述】:
是否可以使用快速彩色文本框在 WPF 中进行语法高亮。
http://www.codeproject.com/Articles/161871/Fast-Colored-TextBox-for-syntax-highlighting
我找不到适用于 WPF c# 的示例。
【问题讨论】:
标签: syntax highlighting
是否可以使用快速彩色文本框在 WPF 中进行语法高亮。
http://www.codeproject.com/Articles/161871/Fast-Colored-TextBox-for-syntax-highlighting
我找不到适用于 WPF c# 的示例。
【问题讨论】:
标签: syntax highlighting
是的,但您必须使用名为 WindowsFormsHost 的 WPF 组件。
在代码中创建FastColoredTextBox 的实例并将其添加到Windows 窗体宿主对象中,如下例所示:
FastColoredTextBox textBox = new FastColoredTextBox();
windowsFormsHost.Child = textBox;
textBox.TextChanged += Ts_TextChanged;
textBox.Text = "public class Hello { }";
【讨论】:
您需要创建一个自定义WindowsFormsHost 控件并将您的绑定作为依赖属性添加到此自定义控件,以将其传递给FastColoredTextBox。
here 解释了一个更一般的示例。
但是对于这个绑定Text属性的具体问题:
using System.Windows;
using System.Windows.Forms.Integration;
using FastColoredTextBoxNS;
namespace ProjectMarkdown.CustomControls
{
public class CodeTextboxHost : WindowsFormsHost
{
private readonly FastColoredTextBox _innerTextbox = new FastColoredTextBox();
public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CodeTextboxHost), new PropertyMetadata("", new PropertyChangedCallback(
(d, e) =>
{
var textBoxHost = d as CodeTextboxHost;
if (textBoxHost != null && textBoxHost._innerTextbox != null)
{
textBoxHost._innerTextbox.Text = textBoxHost.GetValue(e.Property) as string;
}
}), null));
public CodeTextboxHost()
{
Child = _innerTextbox;
_innerTextbox.TextChanged += _innerTextbox_TextChanged;
}
private void _innerTextbox_TextChanged(object sender, TextChangedEventArgs e)
{
SetValue(TextProperty, _innerTextbox.Text);
}
public string Text
{
get { return (string) GetValue(TextProperty); }
set
{
SetValue(TextProperty, value);
}
}
}
}
还有 XAML:
<customControls:CodeTextboxHost Text="{Binding MyTextField, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
【讨论】:
我知道它并没有真正回答你的问题,但我发现自己在同样的情况下问这个问题,我改用 AvalonEdit 解决了这个问题。您可以只将 WPF 绑定到 Document 属性,我什至在 Tooltip 中使用它。
这里是一个最小的例子......
WPF:
<ListBox ItemsSource="{Binding SnippetList}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch">
<Grid.ToolTip>
<avalonEdit:TextEditor xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit" Name="FctbPreviewEditor" FontFamily="Consolas" SyntaxHighlighting="C#" FontSize="10pt" Document="{Binding Document}" />
</Grid.ToolTip>
<TextBlock Text="{Binding Label}" Grid.Column="1" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
绑定到的类(ItemSource是SnippetList,即Snippet的List:
public class Snippet
{
public string Label { get; set; }
public string Data { get; set; }
public TextDocument Document {
get {
return new TextDocument(){ Text = this.Data };
}
}
}
【讨论】:
子 = _innerTextbox;
_innerTextbox.TextChanged += _innerTextbox_TextChanged;
对我来说很好用
【讨论】: