首页 > 解决方案 > Visual Studio 未检测到 RichTextBox.Selection 属性。缺少使用参考?

问题描述

我想使用我的RichTextBox. 我在我的项目中添加了对的引用,PresentationFramework.dll并在我的代码中添加了对命名空间 System.Windows.Controls 的使用引用。根据 Microsoft 文档,这应该有效(RichTextBox.Selection 属性

但是,Visual Studio 找不到 myRichTextBox.Selection 并给我一个错误。我错过了一些参考或什么?

抛出错误的代码是这样的:它是一个接收 RTF 文本并将其加载到 RichTextBox 中的函数,具有丰富的格式

 private void LoadRTF(string RTFtext)
 {
     MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RTFtext));
     myRichTextBox.Selection.Load(stream, DataFormats.Rtf);
 } //LoadRTF

但这里的问题是 Visual Studio 无法识别 Selection 属性。即使是简单的线条

 TextSelection ts = myRichTextBox.Selection; 

抛出同样的错误

标签: c#.netwpfwinforms

解决方案


由于您使用的是 Windows 窗体 RichTextBox 控件,因此 Selection 属性不可用。您可以使用SelectedTextSelectedRtf属性来获取当前选择内容。

至于要从 MemoryStream 加载内容到控件的部分,可以使用LoadFileLoadFile(Stream, RichTextBoxStreamType)方法的重载,如下所示:

private void LoadRTF(string RTFtext)
{
    MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RTFtext));
    myRichTextBox.LoadFile(stream, RichTextBoxStreamType.RichText);
}

最后,如果您真的想在 Winforms 应用程序中使用 WPF RichTextBox 控件,您可以使用 ElementHost 控件来实现,如此所述。


推荐阅读