XAML 未能找到RichTextBox.SelectionStart

6bc51xsx  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(131)

我的代码不允许我以编程方式在RichTextBox中设置SelectionStart和SelectionLength,是否有特殊原因?

text = System.IO.File.ReadAllText(path);
            prompterText.AppendText(File.ReadAllText(@path));
            prompterText.FontSize = textSize;
            prompterText.HorizontalAlignment = HorizontalAlignment.Center;
            prompterText.Focus();

            this.prompterText.SelectionStart = 0;
            this.prompterText.SelectionLength = 50;
            this.prompterText.SelectionBrush = System.Windows.Media.Brushes.Aqua ;

在选择起始行,它告诉我"RichTextBox不包含SelectionStart的定义,并且找不到接受RichTextBox作为第一个参数的扩展方法"。
这很奇怪,因为我发现很多代码示例在RichTextBoxes上使用了完全相同的行。

<ScrollViewer x:Name="scroller" Margin="0">
        <RichTextBox x:Name="prompterText" Margin="10" IsReadOnly="False"/>
    </ScrollViewer>

在XAML代码中,我将IsReadOnly设置为false,以确保我有访问权限,但仍然存在相同的问题。
我的意图是让一个文本选择在一个提示类型窗口中运行,以设置一个特定的阅读器速度。

oknwwptz

oknwwptz1#

RichTextBox SelectionStart属性仅在winforms中可用。对于WPF,我们需要使用TextPointer进行选择。请参考以下代码。

prompterText.AppendText("1111111111111111111111111111111111111111111111111111111111111111111111");           
prompterText.HorizontalAlignment = HorizontalAlignment.Center;
prompterText.Focus();
TextPointer text = prompterText.Document.ContentStart;
while (text.GetPointerContext(LogicalDirection.Forward) != TextPointerContext.Text)
{
    text = text.GetNextContextPosition(LogicalDirection.Forward);
}
TextPointer startPos = text.GetPositionAtOffset(0);
TextPointer endPos = text.GetPositionAtOffset(10); 
prompterText.Selection.Select(startPos, endPos);
this.prompterText.SelectionBrush = System.Windows.Media.Brushes.Aqua;

相关问题