WPF表列大小

时间:2010-09-29 14:34:35

标签: wpf flowdocument

我正在使用代码隐藏在WPF Table中呈现FlowDocument。但是,我一直无法找到一个示例,说明如何使表只使用所需的空间based on content。相反,该表占用了我不想要的所有可用宽度,我也不想指定精确的像素大小。

我显然遗漏了一些简单的东西,有人看到了吗?

var fd = new FlowDocument();

Table t = new Table();

t.BorderBrush = Brushes.Black;
t.BorderThickness = new Thickness(2);

// I thought this would do what I wanted...
t.Columns.Add(new TableColumn() { Width = GridLength.Auto });
t.Columns.Add(new TableCOlumn() { Width = GridLength.Auto });

TableRowGroup trg = new TableRowGroup();

TableRow currentRow = new TableRow();
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("ABC"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("XYZ"))));
trg.Rows.Add(currentRow);

currentRow = new TableRow();
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("123"))));
currentRow.Cells.Add(new TableCell(new Paragraph(new Run("789"))));
trg.Rows.Add(currentRow);

t.RowGroups.Add(trg);

fd.Blocks.Add(t);

3 个答案:

答案 0 :(得分:9)

我不认为这是可能的...唯一的hacky解决方法是使用BlockUIContainer和一个真正的网格!

var fd = new FlowDocument();

Grid g = new Grid();

g.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
g.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });

g.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
g.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });

var t1 = new TextBlock() { Text = "ABC", Margin = new Thickness(5,3,5,3) };
t1.SetValue(Grid.ColumnProperty, 0);
t1.SetValue(Grid.RowProperty, 0);
g.Children.Add(t1);

var t2 = new TextBlock() { Text = "XYZ", Margin = new Thickness(5, 3, 5, 3) };
t2.SetValue(Grid.ColumnProperty, 1);
t2.SetValue(Grid.RowProperty, 0);
g.Children.Add(t2);

var t3 = new TextBlock() { Text = "123", Margin = new Thickness(5, 3, 5, 3) };
t3.SetValue(Grid.ColumnProperty, 0);
t3.SetValue(Grid.RowProperty, 1);
g.Children.Add(t3);

var t4 = new TextBlock() { Text = "789", Margin = new Thickness(5, 3, 5, 3) };
t4.SetValue(Grid.ColumnProperty, 1);
t4.SetValue(Grid.RowProperty, 1);
g.Children.Add(t4);

fd.Blocks.Add(new BlockUIContainer(g));

答案 1 :(得分:3)

尝试TableCell.ColoumnSpan和TableCell.RowSpan

答案 2 :(得分:0)

我知道这个问题是在9年前提出的,但是我发现了一种不使用BlockUIContainer的替代方法,坦白地说,当序列化FlowDocument或用户只是在RichTextBox中编辑文档时,这很痛苦。

向每个表单元格添加一个PreviewMouseMove和PreviewMouseDown处理程序。在PreviewMouseMove中,只要与单元格边界相邻,就将光标更改为SizeWE。在PreviewMouseDown中,使用RichTextBox作为源捕获鼠标。

向RichTextBox添加一个PreviewMouseMove和PreviewMouseUp处理程序。在PreviewMouseMove中,根据计算出的水平增量移动来调整表格列的大小。在PreviewMouseUp中释放鼠标。

棘手的部分是弄清楚单元格边界的位置,因为没有开箱即用的方法来获取单元格的位置或宽度。因此,您必须通过计算PagePadding,Table Padding和列宽的总和来估算它们的位置。