2014-01-07 20 views
0

截至目前,我使用下面的代碼調用我的轉換器,它爲我做了這件事,把我需要的行號。在DataGrid中添加一個ViewModel成員的行號作爲行號

<DataGridTextColumn Header="NO" Width="22" IsReadOnly="True" x:Name="rowNumber"> 
        <DataGridTextColumn.HeaderStyle> 
         <Style TargetType="{x:Type DataGridColumnHeader}"> 
          <Setter Property="FontSize" Value="10" /> 
          <Setter Property="Margin" Value="0"/> 
         </Style> 
        </DataGridTextColumn.HeaderStyle> 
        <DataGridTextColumn.Binding> 
         <MultiBinding Converter="{StaticResource rowNumberConverter}"> 
          <Binding /> 
          <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" /> 
         </MultiBinding> 
        </DataGridTextColumn.Binding> 
       </DataGridTextColumn> 

和轉換器:

class RowNumberConverter : IMultiValueConverter 
    { 
     #region IMultiValueConverter Members 

     public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
     { 

      //get the grid and the item 
      Object item = values[0]; 
      DataGrid grid = values[1] as DataGrid; 

      int index = grid.Items.IndexOf(item) + 1 ; 

      return index.ToString().PadLeft(2, '0'); 
     } 

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

     #endregion 
    } 

然而,這將無法在我們的新的要求,分頁。該轉換器當然不會繼續計數,因爲它只引用DataGrid中的行。

任何人都可以指出我如何使行數繼續在下一頁? 堅持清潔MVVM模式是必要的。

感謝您的幫助。

+0

OMG,這是可怕的,絕對*不* MVVM!你不應該像這樣訪問轉換器中的UI元素。嘗試綁定到'DataGrid.ItemsSource'或'DataGrid.Items'屬性,而不是整個'DataGrid'。 – Sheridan

+0

看看這裏:[?如何在ListView顯示行號] [1] [1]:http://stackoverflow.com/questions/660528/how-to-display-row-數字在列表視圖 – gomi42

回答

0

我認爲一個視圖模型只是作爲提供要顯示的數據的全部的元素。如果需要顯示項目編號,則只需將其他屬性添加到正在顯示的元素即可。

這樣做可以讓您用任何您想要的值填充數字,無論連續序列中是否有數字,或者您是否有更復雜的編號系統。

+0

是否合理,我可以避免你上面指出的醜陋。我試圖找出是否有辦法動態地添加這些數字。 – eemwingg

+0

只有在視圖模型中循環訪問您的集合,並且每次都設置相關的編號。 – Sheridan

+0

是的,這就是我所做的。我想看看是否有辦法只修補視圖。一如既往,再次感謝您的幫助。 – eemwingg