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

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

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

谁能帮我实现这个目标?谢谢

最佳答案

可能有一种更简单的方法来执行此操作,但是我可以通过在DataGridRow类上使用GetIndex()方法来使其工作。这会将索引返回到数据源中,因此可能与您要查找的不完全相同。

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 - 如何在WPF Datagrid的第一列中显示行号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15061013/

10-13 07:48
查看更多