I'm trying to create a Table
inside a FlowDocument
inside a FlowDocumentPageViewer
, as seen in this tutorial. I've never created a table in WPF before, and I was expecting there to be an ItemsSource
property to which I could bind, like with a ListBox
. I want to customize the template for each row, and I want each row's source to be an item in a collection that I pass to the entire table. So I'll have a List<MyClass>
instance that would be passed to the table, and each row would show a single MyClass
. How can I do that? Do I not want to use a Table
within a FlowDocument
? The reason I wanted to use some kind of tabular format is so that I can have a single row of column names that applies to all the rows.
views:
48answers:
2
A:
Binding to the table isn't simple. Use code-behind:
public MainWindow()
{
InitializeComponent();
var items = Enumerable.Range(0, 5).Select(i => new { Id = i, Title = "title " + i, Description = "some description" }).ToList();
flowDoc.DataContext = items;
var table =
"<Table xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>"+
" <Table.Columns>"+
" <TableColumn Width='120'/>"+
" <TableColumn Width='120'/>"+
" <TableColumn Width='220'/>"+
" </Table.Columns>"+
string.Concat(Enumerable.Range(0, items.Count).Select(index=>
" <TableRowGroup Background='White' DataContext='{Binding Path=["+index+"]}'>"+
" <TableRow>"+
" <TableCell>"+
" <Paragraph>"+
" <TextBlock Text='{Binding Id}'/>"+
" </Paragraph>"+
" </TableCell>"+
" <TableCell>"+
" <Paragraph>"+
" <TextBlock Text='{Binding Title}'/>"+
" </Paragraph>"+
" </TableCell>"+
" <TableCell>"+
" <Paragraph>"+
" <TextBlock Text='{Binding Description}'/>"+
" </Paragraph>"+
" </TableCell>"+
" </TableRow>"+
" </TableRowGroup>"))+
"</Table>";
var xamlTable = XamlReader.Parse(table) as Table;
flowDoc.Blocks.Add(xamlTable);
}
Xaml:
<FlowDocumentPageViewer>
<FlowDocument x:Name="flowDoc" />
</FlowDocumentPageViewer>
But I think it is better to use ItemsControl because it supports ObservableCollection.
vorrtex
2010-09-07 21:04:14
A:
I think what I wanted was to use ListView
, thanks to this tutorial:
<ListView Grid.Row="0" ItemsSource="{Binding Path=MyList}" MinWidth="400"
MinHeight="200">
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn
DisplayMemberBinding="{Binding Path=MyFirstField}"
Header="First Field"/>
<GridViewColumn
DisplayMemberBinding="{Binding Path=MySecondField}"
Header="Second Field"/>
</GridView.Columns>
</GridView>
</ListView.View>
</ListView>
Sarah Vessels
2010-09-07 21:28:51