WPF拖動DataGrid滾動條時內容混亂的解決方法
在WPF中,如果DataGrid裡使用了模板列,當拖動滾動條時,往往會出現列表內容顯示混亂的情況。解決方法就是在Binding的時候給UpdateSourceTrigger賦值。
<Grid> <Grid.RowDefinitions> <RowDefinition Height="25"></RowDefinition> <RowDefinition></RowDefinition> </Grid.RowDefinitions> <Button Height="23" Click="Button_Click" Content="Click" Grid.Row="0"></Button> <DataGrid Name="dgStudent" AutoGenerateColumns="False" IsEnabled="True" Grid.Row="1" EnableColumnVirtualization="True" EnableRowVirtualization="True"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="80"></DataGridTextColumn> <DataGridTemplateColumn Header="Age" Width="70"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBox Margin="5" Text="{Binding Age, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></TextBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> <DataGridTemplateColumn Header="Course" Width="100"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <ComboBox Margin="5" ItemsSource="{Binding CourseSource}" Text="{Binding Course, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"></ComboBox> </DataTemplate> </DataGridTemplateColumn.CellTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </Grid>
後台代碼如下:
public class Student { public string Name { get; set; } public string Age { get; set; } public List<string> CourseSource { get; set; } = new List<string>() { "C", "C++", "C#" }; public string Course { get; set; } } private void Button_Click(object sender, RoutedEventArgs e) { var students = new List<Student>(); for (int i = 1; i <= 50; i++) { var student = new Student() { Name = $"student{i}" }; students.Add(student); } this.dgStudent.ItemsSource = null; this.dgStudent.ItemsSource = students; }