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

标签 wpf xaml mvvm datagrid

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

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

最佳答案

同样的问题,我有...

RelativeSource={RelativeSource AncestorType=DataGrid}

它没有用,所以我尝试了...
RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}

......它奏效了。

关于wpf - 选中数据网格标题中的所有复选框在 wpf mvvm 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043530/

相关文章:

c# - 在 XAML 中移动标签

c# - DataGridComboBoxColumn 绑定(bind)转换器未按预期工作

ios - 用 ReactiveCocoa 观察 Realm 的属性对象,当对象失效时如何处理

c# - 使用查询字符串打开 html 文件

c# - 如何在 WPF 中使用 XNA?

c# - XAML 将 Rectange.Fill SolidColorBrush 绑定(bind)到 Color 属性

xaml - Xamarin.Forms - 将元素放置在另一个元素之上。

mvvm - 领域模型对 View 模型的依赖有多糟糕?

wpf - 在 XAML 中呈现分隔列表?

wpf - 为什么WPF TreeView控件继承自ItemsControl而不是Selector?