Datagrid无法正确更新,滚动时更新

时间:2016-05-05 08:27:04

标签: c# wpf mvvm datagrid

我正在使用'mvvm'模式在wpf中的datagrid中实现一个select all复选框。我面临的问题是检查标题“全选”复选框,所有复选框都被选中,但只有在向下滚动滚动条后才能检查。如何解决这个问题?

选中“全选”后向下滚动

[

再滚动后再次

[

 private bool _IsSelected;
    public bool IsSelected
    {
        get { return _IsSelected; }
        set
        {
            _IsSelected = value;
            OnPropertyChanged("IsSelected");
        }
    }

    private bool _AllSelected;
    public bool AllSelected
    {
        get { return _AllSelected; }
        set
        {
            _AllSelected = value;
            foreach (var reportListItemModel in UsecaseListItems)
            {
                reportListItemModel.IsSelected = this._AllSelected;
                OnPropertyChanged("IsSelected");
            }
            OnPropertyChanged("AllSelected");

        }
    }


    private ObservableCollection<UseCase> _usecaseListItems = new ObservableCollection<UseCase>();
    public ObservableCollection<UseCase> UsecaseListItems
    {
        get { return _usecaseListItems; }
        set {
            _usecaseListItems = value;
            OnPropertyChanged("UsecaseListItems");
        }
    }

Xaml代码

<DataGrid Grid.Row="0" ItemsSource="{Binding Path=UsecaseListItems, Mode=OneWay, NotifyOnSourceUpdated=True, UpdateSourceTrigger=PropertyChanged}" AutoGenerateColumns="False" Name="MyDataGrid"
          CanUserAddRows="False" >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding Path=IsSelected,UpdateSourceTrigger=PropertyChanged, Mode=TwoWay,IsAsync=True}"  Width="50">
                <DataGridCheckBoxColumn.HeaderTemplate>
                    <DataTemplate x:Name="dtAllChkBx">
                        <CheckBox Name="cbxAll" Content="All" IsChecked="{Binding Path=DataContext.AllSelected,RelativeSource={RelativeSource AncestorType=UserControl },Mode=TwoWay}"/>
                    </DataTemplate>
                </DataGridCheckBoxColumn.HeaderTemplate>
            </DataGridCheckBoxColumn>
            <DataGridTemplateColumn Header="Name" Width="SizeToCells" IsReadOnly="True">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding UsecaseName}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

1 个答案:

答案 0 :(得分:0)

这是我在DataGrid行(本例中为UseCase)中表示的模型未实现INotifyPropertyChanged时观察到的行为。它们在滚动期间更新,因为它们被重新绘制,并且当时从属性中读取新值。