Hello,
I am using WPF with MVVM.
How can I bind:
- a list of numbers
- or a list of clr objects with property number
- or a list of strings
in my ViewModel to the RowHeader of the WPF DataGrid ?
Hello,
I am using WPF with MVVM.
How can I bind:
in my ViewModel to the RowHeader of the WPF DataGrid ?
You could take this approach http://www.codeproject.com/KB/WPF/MVVM_DataGrid.aspx?msg=3241301
Basically you are creating an list that will handle the numbering for you, as long as the object of T implements ISequenceObject.
If you wanted to go the other direction you could look at handling the LoadingRow Event and simply adding 1 to a known DataColumn. This would not break the concept of MVVM as a numbered column is not part of the business logic, but part of the presentation.
To make the Numbered DataGrid reusable you could also inherit from the DataGrid and create you own Numbered DataGrid.
I found an elegant solution for this problem from http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/7d0cbdf2-dea3-4dd4-a570-08aa6c78d911. Here is recap:
<tk:DataGrid x:Name="dg" LoadingRow="dg_LoadingRow" ItemsSource="{Binding}">
<tk:DataGrid.RowHeaderTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type tk:DataGridRow}}, Path=Header}"></TextBlock>
</DataTemplate>
</tk:DataGrid.RowHeaderTemplate>
</tk:DataGrid>
private void dg_LoadingRow(object sender, Microsoft.Windows.Controls.DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
However, I couldn't make the number on the row header right aligned. Adding HorizontalAlignment="Right" to the TextBlock doesn't help. I also tried to wrap the TextBlock inside a StackPanel, and set this property, but it doesn't work either. Any idea?