码迷,mamicode.com
首页 > Windows程序 > 详细

WPF拖动DataGrid滚动条时内容混乱的解决方法

时间:2016-10-12 11:02:44      阅读:283      评论:0      收藏:0      [点我收藏+]

标签:

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;
        }

 

WPF拖动DataGrid滚动条时内容混乱的解决方法

标签:

原文地址:http://www.cnblogs.com/zhou-yi/p/5951717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!