选择数据网格标题中的所有复选框在wpf mvvm中无法正常工作

时间:2016-05-05 06:06:11

标签: wpf xaml mvvm datagrid

This is what i want我正在研究wpf mvvm datagrid并尝试将select all复选框与视图模型绑定。它没有给我正确的结果。我在这里给出了我的代码详细信息(xaml代码和视图模型代码)

 <DataGrid Grid.Row="0" ItemsSource="{Binding Path=UsecaseListItems}" AutoGenerateColumns="False" Name="MyDataGrid"
          CanUserAddRows="False" >
        <DataGrid.Columns>
            <DataGridCheckBoxColumn Binding="{Binding IsSelected}" Width="50" >
                <DataGridCheckBoxColumn.HeaderTemplate>
                    <DataTemplate x:Name="dtAllChkBx">
                        <CheckBox Name="cbxAll" Content="All" IsChecked="{Binding Path=DataContext.AllSelected,RelativeSource={RelativeSource AncestorType=DataGrid},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>


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");

        }
    }


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

3 个答案:

答案 0 :(得分:1)

同样的问题,我有...

RelativeSource={RelativeSource AncestorType=DataGrid}

它没有用,所以我尝试了...

RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}

...而且有效。

答案 1 :(得分:0)

由于视图模型中的allselected属性,您必须将ancestortype提供给窗口或用户控件而不是datagrid ...

答案 2 :(得分:0)

检查触发事件OnPropertyChanged("IsSelected");。而不是使用它,给OnPropertyChanged("AllSelected");。同时将祖先类型赋予窗口或用户控制它可能是什么......