我有一个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();
}
答案 0 :(得分:3)
TableRow
个实例位于RowGroup
个实例内的Table
个实例中。表格是块。
您可以尝试以下代码:
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();
}
<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();
}
}
}