【发布时间】:2014-01-07 09:09:18
【问题描述】:
目前,我正在使用以下代码调用我的转换器,它为我做这件事,输入我需要的行号。
<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 模式是必要的。
感谢您的帮助。
【问题讨论】:
-
天啊,这太可怕了,绝对不是 MVVM!您不应该在这样的转换器中访问 UI 元素。尝试绑定到
DataGrid.ItemsSource或DataGrid.Items属性而不是整个DataGrid。 -
看看这里:[如何在 ListView 中显示行号?][1] [1]:stackoverflow.com/questions/660528/…
标签: c# wpf mvvm datagrid rowcount