I have a WPF richtextbox having a Table as a Flowdocument. I need to copy content of selected table rows using C# on mouse right click.
The problem I m facing is being unable to get selected rows.
Using following function but unable to get selected rows of Richtextbox.
Any help would be appreciated.
Thanks in advance
public static List<TableRow> GetSelectedParagraphs(FlowDocument document, TextSelection selection)
{
return document.Blocks.OfType<TableRow>().Where(w => selection.Contains(w.ContentStart)).ToList();
}
TableRow
instances are inside RowGroup
instances that are inside Table
instances. And tables are blocks.
You can try the code below:
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();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.