c#在wpf datagrid中选择所有复选框的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/756033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 23:58:55  来源:igfitidea点击:

c# code for select all checkbox in wpf datagrid

c#wpf.net-3.5datagridcheckbox

提问by

I need some c# code to select / deselect all checkboxes in a datagrid in WPF 3.5 framework. I would like to do this by clicking a single header checkbox in the grid.

我需要一些 C# 代码来选择/取消选择 WPF 3.5 框架中数据网格中的所有复选框。我想通过单击网格中的单个标题复选框来做到这一点。

Please help.

请帮忙。

回答by Jeff Wain

This is based on someone else's source that I can't recall, but we use it to help find visual children of a type. It may not be the most efficient use for this scenario but it might help get you on the right track.

这是基于我不记得的其他人的来源,但我们用它来帮助找到某种类型的视觉儿童。对于这种情况,它可能不是最有效的用法,但它可能有助于让您走上正轨。

    public static childItem FindVisualChild<childItem>(DependencyObject obj) where childItem : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            if (child != null && child is childItem)
                return (childItem)child;

            childItem childOfChild = FindVisualChild<childItem>(child);
            if (childOfChild != null)
                return childOfChild;
        }
        return null;
    }

[Edit 4.16.09] Based on that, try out this method. Should find all CheckBoxes and change the state as provided, callable from your event handler on the Checked/Unchecked events.

[Edit 4.16.09] 基于此,尝试此方法。应该找到所有 CheckBoxes 并更改所提供的状态,可从 Checked/Unchecked 事件的事件处理程序调用。

   public static void CheckAllBoxes(DependencyObject obj, bool isChecked)
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
        {
            // If a checkbox, change IsChecked and continue.
            if (obj is CheckBox)
            {
                ((CheckBox) obj).IsChecked = isChecked;
                continue;
            }

            DependencyObject child = VisualTreeHelper.GetChild(obj, i);
            CheckAllBoxes(child, isChecked);
        }
    }

回答by Jacob Adams

I would use the new databinding features in WPF. Give all of the checkboxes a one-way binding on their IsChecked property with the binding source being the master checkbox's IsChecked property.

我会在 WPF 中使用新的数据绑定功能。为所有复选框对其 IsChecked 属性进行单向绑定,绑定源是主复选框的 IsChecked 属性。

Another option would be to use triggers

另一种选择是使用触发器

回答by Pradeep

This can be done declaratively. The following creates a checkbox column for each row and which can toggle row selections. The header of the checkbox column can be clicked to do a select all of the rows.

这可以声明性地完成。下面为每一行创建一个复选框列,可以切换行选择。可以单击复选框列的标题来选择所有行。

Relevant portions from the xaml

来自 xaml 的相关部分

<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:toolkit="http://schemas.microsoft.com/wpf/2008/toolkit">
    <toolkit:DataGrid Name="dataGrid" 
     ItemsSource="{Binding}" AutoGenerateColumns="True" 
     SelectionMode="Extended" CanResizeRows="False">
    <toolkit:DataGrid.RowHeaderTemplate>
       <DataTemplate>
           <Grid>
               <CheckBox IsChecked="{
                  Binding Path=IsSelected, 
                  Mode=TwoWay, 
                  RelativeSource={RelativeSource FindAncestor, 
                  AncestorType={x:Type toolkit:DataGridRow}}}"
            />
           </Grid>
       </DataTemplate>
    </toolkit:DataGrid.RowHeaderTemplate>
    </toolkit:DataGrid>
</Window>

回答by AZ_

DataColumn dt = null;            
        for (int i = 0; i < dataGrid.Columns.Count; i++)
        {

     dt = new DataColumn("Column Name");

            dt.DataType = typeof(Boolean);
            dt.DefaultValue = false;
             dataTable.Add(dt);
        }

dataGied.DataContext = dataTable;



<Custom:DataGrid x:Name="dataGrid" AutoGenerateColumns="True" ItemsSource="{Binding}" />                    

Well it is just a rough Idea, hope this works

嗯,这只是一个粗略的想法,希望这有效

回答by Lance Cleveland

Here is the sample datagrid we use in the .Net 4.0 XAML file:

这是我们在 .Net 4.0 XAML 文件中使用的示例数据网格:

<DataGrid Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" Name="dgMissingNames" ItemsSource="{Binding Path=TheMissingChildren}" Style="{StaticResource NameListGrid}" SelectionChanged="DataGrid_SelectionChanged">
    <DataGrid.Columns>
        <DataGridTemplateColumn CellStyle="{StaticResource NameListCol}">
            <DataGridTemplateColumn.HeaderTemplate>
                <DataTemplate>
                    <CheckBox Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked" />
                </DataTemplate>                            
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>                        
                <DataTemplate>
                    <CheckBox IsChecked="{Binding Path=Checked, UpdateSourceTrigger=PropertyChanged}" Name="theCheckbox"/>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>                            
        </DataGridTemplateColumn>
        <DataGridTextColumn Binding="{Binding Path=SKU}" Header="Album" CellStyle="{StaticResource NameListCol}"/>
        <DataGridTextColumn Binding="{Binding Path=Name}" Header="Name" CellStyle="{StaticResource NameListCol}"/>
        <DataGridTextColumn Binding="{Binding Path=Pronunciation}" Header="Pronunciation" CellStyle="{StaticResource NameListCol}"/>
    </DataGrid.Columns>
</DataGrid>

Here is the codebehind:

这是代码隐藏:

private void HeadCheck(object sender, RoutedEventArgs e, bool IsChecked)
{
    foreach (CheckedMusicFile mf in TheMissingChildren)
    {
        mf.Checked = IsChecked;
    }
    dgMissingNames.Items.Refresh();
}

private void CheckBox_Checked(object sender, RoutedEventArgs e)
{
    HeadCheck(sender, e, true);
}

private void CheckBox_Unchecked(object sender, RoutedEventArgs e)
{
    HeadCheck(sender, e, false);
}

TheMissingChildren is a simple object structure with some string properties and an ischecked boolean.

TheMissingChildren 是一个简单的对象结构,具有一些字符串属性和一个 ischecked 布尔值。

HTH.

哈。