【问题标题】:Column/Row index in a DataGrid columnDataGrid 列中的列/行索引
【发布时间】:2014-03-06 02:41:00
【问题描述】:

我希望以下内容可以让我获得单元格中的列索引:

<DataGridTemplateColumn Header="Rec. No." Width="100" IsReadOnly="True">
     <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
              <TextBlock Text="{Binding Source={RelativeSource AncestorType=DataGridCell}, Path=Column.DisplayIndex}" />
         </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

但它没有。谁能告诉我这里出了什么问题?

我实际上是在寻找行索引(在我的网格中需要一个记录号列),但由于 DataGridRow 显然没有“索引”类型的属性,我尝试首先为列做索引,有DisplayIndex。但即使是这个也行不通。

【问题讨论】:

    标签: .net wpf xaml binding datagrid


    【解决方案1】:

    绑定语法不正确。而不是Source,应该是RelativeSource

    Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, 
                   Path=Column.DisplayIndex}"
    

    对于获取RowIndex 的第二个问题,DataGridRow 上没有 RowIndex 等内置属性。

    我建议在底层数据类中拥有一些属性并绑定到它。

    但是,您也可以通过设置 IValueConverter 手动获取 rowIndex。

    public class RowIndexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, 
                              System.Globalization.CultureInfo culture)
        {
            DependencyObject item = (DependencyObject)value;
            ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);
    
            return ic.ItemContainerGenerator.IndexFromContainer(item);
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, 
                                  System.Globalization.CultureInfo culture)
        {
            return Binding.DoNothing;
        }
    }
    

    XAML:

    <TextBlock
         Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, 
                              Converter={StaticResource RowIndexConverter}}"/>
    

    当然,您需要在 XAML 的资源部分声明 Converter 的实例才能使用它。

    【讨论】:

    • 谢谢。这样就解决了一半的问题。现在您看到任何获取行索引的方法了吗?
    • DataGridRow 上没有内置属性。您可以在基础数据类中拥有索引属性,也可以使用 Converter 来手动获取行索引。
    • 已在答案中更新..!!
    猜你喜欢
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2016-03-28
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多