Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF DataGrid RowHeader databinding

I have a DataGrid, bound to a DataTable. I want to display text in the RowHeader, to achieve something like this:

         Col0      Col1      Col2      Col3 Table |    1    |    3    |    5    |    6    | Chair |    3    |    2    |    1    |    8    | 

Is this possible and if so, how can I do this?

like image 776
eriksmith200 Avatar asked Jan 25 '11 09:01

eriksmith200


2 Answers

I tried both answers, and neither worked for me. Essentially what I had to do was mix them together.

This works for me:

<DataGrid name="ui_dataGrid>     <DataGrid.RowHeaderTemplate>         <DataTemplate>             <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,                                        AncestorType={x:Type DataGridRow}},                                        Path=Item.Header}"/>         </DataTemplate>     </DataGrid.RowHeaderTemplate> </DataGrid> 

The trick is to find the ancestor DataGridRow, then Bind the TextBlock.Text attribute to its Item's property that you care about, in this case Header (easier said in XAML than English maybe).

Then in the .xaml.cs:

ui_dataGrid.ItemsSource = dataSource.Rows; 

N.B. Each Row object has a Header property which is what I'm binding too.

like image 82
markmuetz Avatar answered Sep 22 '22 06:09

markmuetz


2 ways to do it, the prev example almost had it but the binding would fail to resolve the property because the expression was missing "DataContext."

<DataGrid>         <DataGrid.RowHeaderTemplate>             <DataTemplate>                 <TextBlock Text="{Binding DataContext.YourProperty}"></TextBlock>             </DataTemplate>         </DataGrid.RowHeaderTemplate>          <!--your stuff--> </DataGrid> 

2nd way to do it is to create a converter to get the binding, parse it in the converter and spit out whatever string value you want:

<Views:DataGridRowDataContextToRowHeaderValueConverter x:Key="toRowHeaderValue"/>  <DataGrid.RowHeaderTemplate>         <DataTemplate>             <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,                        AncestorType={x:Type DataGridRow}},                        Converter={StaticResource toRowHeaderValue}}"/>         </DataTemplate> </DataGrid.RowHeaderTemplate> 

Sample converter code:

public class DataGridRowDataContextToRowHeaderValueConverter : IValueConverter {     public object Convert (object value, Type targetType, object parameter,                             CultureInfo culture)     {              var dataGridRow = (DataGridRow) value;         var row = (GridModelExtensions.HourRow) dataGridRow.DataContext;         return row.Days[0].Hour;     } } 
like image 38
denis morozov Avatar answered Sep 22 '22 06:09

denis morozov