如何在 WPF Datagrid 的第一列中显示行号 [英] How to show row-number in first column of WPF Datagrid

查看:101
本文介绍了如何在 WPF Datagrid 的第一列中显示行号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

搜索时发现,行号可以轻松设置为RowHeader:

While searching I found that, row number can be set to RowHeader easily:

void datagrid_LoadingRow(object sender, DataGridRowEventArgs e) 
{ 
     e.Row.Header = e.Row.GetIndex(); 
} 

它在 RowHeader 中设置行号.但我想将行号显示到第一列

It sets row number in RowHeader. But I want to show Row number to first column

任何人都可以帮助我如何实现这一目标?谢谢

Can any one help me how can I achieve this? Thanks

推荐答案

可能有更简单的方法来执行此操作,但我通过使用 DataGridRow 类上的 GetIndex() 方法使其工作.这会将索引返回到数据源,因此可能不是您想要的.

There might be an easier way to do this but I got it to work by using the GetIndex() method on the DataGridRow class. This returns the index in to the data source so might not be exactly what you're after.

xaml

  <Window x:Class="WpfApplication1.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:sys="clr-namespace:System;assembly=mscorlib"
            xmlns:local="clr-namespace:WpfApplication1"
            Title="MainWindow" Height="350" Width="525">
        <DataGrid>
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, Converter={local:RowToIndexConverter}}" />
            </DataGrid.Columns>
            <DataGrid.Items>
                <sys:String>a</sys:String>
                <sys:String>b</sys:String>
                <sys:String>c</sys:String>
                <sys:String>d</sys:String>
                <sys:String>e</sys:String>
            </DataGrid.Items>
        </DataGrid>
    </Window>

和转换器.

public class RowToIndexConverter : MarkupExtension, IValueConverter
{
    static RowToIndexConverter converter;

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        DataGridRow row = value as DataGridRow;
        if (row != null)
            return row.GetIndex();
        else
            return -1;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (converter == null) converter = new RowToIndexConverter();
        return converter;
    }

    public RowToIndexConverter()
    {
    }
}

这篇关于如何在 WPF Datagrid 的第一列中显示行号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆