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?
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.
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; } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With