How to display row numbers in a ListView?

前端 未结 10 904
盖世英雄少女心
盖世英雄少女心 2020-11-27 04:33

The obvious solution would be to have a row number property on a ModelView element, but the drawback is that you have to re-generate those when you add records or change sor

10条回答
  •  时光说笑
    2020-11-27 05:25

    Here's my little converter which works great as of WPF in 2017 with .NET 4.7.2, including with the VirtualizingStackPanel fully enabled:

    [ValueConversion(typeof(IList), typeof(int))]
    public sealed class ItemIndexConverter : FrameworkContentElement, IValueConverter
    {
        public Object Convert(Object data_item, Type t, Object p, CultureInfo _) =>
            ((IList)DataContext).IndexOf(data_item);
    
        public Object ConvertBack(Object o, Type t, Object p, CultureInfo _) =>
            throw new NotImplementedException();
    };
    

    Add an instance of this IValueConverter to the Resources of the GridViewColumn.CellTemplate, or elsewhere. Or, instantiate it in-situ on the Binding of the bound element, like I show here. In any case, you need to create an instance of the ItemIndexConverter and don't forget to bind the whole source collection to it. Here I'm pulling a reference to the source collection out of the ItemsSource property of the ListView--but this entails some unrelated hassles over accessing the XAML root, so if you have a better and easier way to refer to the source collection, you should do so.

    As for accessing a property on the XAML root, the ListView root in XAML is given the name w_root, and the XAML 2009 markup extension {x:Reference ...} is used to access the XAML root element. I don't think "ElementName" binding will work here since the reference occurs in a template context.

    
    
        
           
              
                 
                    
                       
                          
                             
                                
                                   
                               
                            
                         
                      
                   
                
             
          
       
    
    

    That's it! It seems to work pretty quickly with a large number of rows, and again, you can see that the reported indices are correct when arbitrarily scrolling around, and that VirtualizingStackPanel.IsVirtualizing is indeed set to True.

    Not sure the following is actually necessary, but notice that the xmlns= declaration for WPF is updated to indicate XAML 2009, in support of the {x:Reference} usage mentioned above. Do notice that there are two changes; "/winfx/" has to be changed to "/netfx/" when switching from "2006" to "2009".

提交回复
热议问题