我在WPF应用程序中使用DataGrid,使用for循环一个接一个地重新保存DataGridRow,直到最后,目前我使用ICollectionView帮助ICollectionView对数据网格进行排序后,我的for循环不工作。
XAML代码:
<DataGrid VerticalAlignment="Stretch" HorizontalAlignment="Stretch" x:Name="GridTest" ItemsSource="{Binding}" AutoGenerateColumns="False" CanUserSortColumns="False" CanUserResizeRows="False" AreRowDetailsFrozen="True" CanUserResizeColumns="False" CanUserDeleteRows="False" IsReadOnly="True">
<DataGrid.Columns>
<DataGridTextColumn Header="SNo" Width="0.25*" Binding="{Binding Path=SNo}" CanUserResize="False" />
<DataGridTextColumn Header="SalaryAmt" Width="0.25*" Binding="{Binding Path=SalaryAmt}" CanUserResize="False" />
<DataGridTextColumn Header="Name" Width="0.20*" Binding="{Binding Path=Name}" CanUserResize="False"/>
<DataGridTextColumn Header="Address" Width="0.30*" Binding="{Binding Path=Address}" CanUserResize="False"/>
</DataGrid.Columns>
</DataGrid>
代码背后的代码:
namespace SortGrid
{
public partial class TestDG
{
Dictionary<string, GridStructure> Dict1;
ObservableCollection<GridStructure> List1 = new ObservableCollection<GridStructure>();
private ICollectionView _currentView;
_currentView = CollectionViewSource.GetDefaultView(List1);
_currentView.SortDescriptions.Add(new SortDescription("SalaryAmt", ListSortDirection.Ascending));
void DispatchTime_Tick(object sender, EventArgs e)
{
Dict1.Clear();
_currentView.Refresh();
GridColors(GridTest_TierColors, GridTest);
}
private void GridColors(Brush[] col, DataGrid Grid)
{
int colorind = 0;
for (int rowind = 0; rowind < Grid.Items.Count; rowind++)
{
DataGridRow row = (DataGridRow)Grid.ItemContainerGenerator.ContainerFromIndex(rowind);
if (row != null)
{
//conditional formatting here
}
}
}
}
}