WPF Rich文本框文本选择
本文关键字:文本 选择 WPF Rich | 更新日期: 2023-09-27 18:21:08
我有一个WPF richtextbox,其中有一个表作为Flowdocument。我需要使用鼠标右键单击C#复制所选表行的内容。
我面临的问题是无法获取选定的行。
正在使用以下函数,但无法获取Richtextbox的选定行。
如有任何帮助,我们将不胜感激。
提前感谢
public static List<TableRow> GetSelectedParagraphs(FlowDocument document, TextSelection selection)
{
return document.Blocks.OfType<TableRow>().Where(w => selection.Contains(w.ContentStart)).ToList();
}
TableRow
实例在RowGroup
实例内,而Table
实例在CCD2实例内。桌子是积木。
您可以尝试以下代码:
public static List<TableRow> GetSelectedParagraphs(FlowDocument document, TextSelection selection)
{
return document.Blocks
.OfType<Table>()
.SelectMany(x => x.RowGroups)
.SelectMany(x => x.Rows)
.Where(w => selection.Contains(w.ContentStart))
.ToList();
}
更新:完整的示例代码
Xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="Blend.MainWindow">
<StackPanel>
<RichTextBox Name="RichTextBox" SelectionChanged="OnSelectionChanged">
<FlowDocument>
<Table CellSpacing="0">
<Table.Columns>
<TableColumn Width="50" />
<TableColumn Width="50" />
</Table.Columns>
<TableRowGroup>
<TableRow>
<TableCell BorderThickness="1" BorderBrush="Black">
<Paragraph>
<Run>1</Run>
</Paragraph>
</TableCell>
<TableCell BorderThickness="1" BorderBrush="Black">
<Paragraph>
<Run>2</Run>
</Paragraph>
</TableCell>
</TableRow>
<TableRow>
<TableCell BorderThickness="1" BorderBrush="Black">
<Paragraph>
<Run>3</Run>
</Paragraph>
</TableCell>
<TableCell BorderThickness="1" BorderBrush="Black">
<Paragraph>
<Run>4</Run>
</Paragraph>
</TableCell>
</TableRow>
</TableRowGroup>
</Table>
<Paragraph />
</FlowDocument>
</RichTextBox>
<TextBlock><Run>Rows selected: </Run><Run Name="TableRowCount" /></TextBlock>
<TextBlock><Run>Selection Text: </Run><Run Name="SelectionText" /></TextBlock>
</StackPanel>
</Window>
代码隐藏
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Documents;
namespace Blend
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void OnSelectionChanged(object sender, RoutedEventArgs e)
{
TableRowCount.Text = GetSelectedParagraphs(RichTextBox.Document, RichTextBox.Selection).Count.ToString();
SelectionText.Text = RichTextBox.Selection.Text;
}
public static List<TableRow> GetSelectedParagraphs(FlowDocument document, TextSelection selection)
{
return document.Blocks
.OfType<Table>()
.SelectMany(x => x.RowGroups)
.SelectMany(x => x.Rows)
.Where(w => selection.Contains(w.ContentStart))
.ToList();
}
}
}