WPF : 7. DataGrid의 Row번호 매기는 법
- Converter
class RowNumberConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
var row = values[0] as RowData;
var rowList = values[1] as ObservableCollection<RowData>;
return rowList.IndexOf(row).ToString();
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
- Row Header에 표시
<DataGrid.RowHeaderTemplate>
<DataTemplate>
<TextBlock>
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource rowNumberConverter}">
<Binding RelativeSource="{RelativeSource AncestorType={x:Type DataGridRow}}" Path="Item"/>
<Binding RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}" Path="ItemsSource"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</TextBlock>
</DataTemplate>
</DataGrid.RowHeaderTemplate>
- Column에 표시
<DataGridTextColumn Header="Index">
<DataGridTextColumn.Binding>
<MultiBinding Converter="{StaticResource rowNumberConverter}">
<Binding />
<Binding RelativeSource="{RelativeSource AncestorType={x:Type DataGrid}}"
Path="ItemsSource"/>
</MultiBinding>
</DataGridTextColumn.Binding>
</DataGridTextColumn>
댓글남기기