获取 wpf 数据网格中的复选框值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18961501/
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-09-13 09:42:26  来源:igfitidea点击:

Get the Checkbox value in wpf datagrid

c#wpfcheckboxdatagrid

提问by Ahmad Gulzar

i have a datagrid in wpf, i have multiple rows(items) in that datagrid and have one checkbox column in each row. i want to check in all rows if the checkbox is checked in any row then perform action below is my code. Thanks!

我在 wpf 中有一个数据网格,我在该数据网格中有多个行(项目),并且每行中有一个复选框列。如果复选框在任何行中被选中,我想检查所有行然后执行下面的操作是我的代码。谢谢!

WPF Code

WPF代码

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False"
                  CellEditEnding="SaveDeliveryValue" LoadingRow="DataGrid_LoadingRow"
                  Name="ViewOrdersGrid" HorizontalAlignment="Center" Margin="0,10,0,0" 
                  VerticalAlignment="Top" Height="278" Width="520" BorderBrush="#FFA0A0A0">
            <DataGrid.Columns>
                <DataGridTextColumn  Header="Order No" Width="115" Binding="{Binding Path=BONo, Mode=OneWay}" />
                <DataGridTextColumn Header="Order Date" Width="100" Binding="{Binding Path=BODate, Mode=OneWay, StringFormat=d}" />
                <DataGridTextColumn Header="Total Amount" Width="100" Binding="{Binding Path=BOTotal, Mode=OneWay}" />
                <DataGridTextColumn Header="Total Bikes" Width="100" Binding="{Binding Path=BOTatalBikes, Mode=OneWay}" />
                <DataGridCheckBoxColumn Header="Delivered" x:Name="DeliveryValueCheck" Width="70" Binding="{Binding Path=BODelivered, Mode=TwoWay}" />
            </DataGrid.Columns>
        </DataGrid>

C# code

C#代码

private void Window_Loaded(object sender, RoutedEventArgs e)
        {

            for (int i = 0; i < ViewOrdersGrid.Items.Count; i++)
            {
                CheckBox mycheckbox = ViewOrdersGrid.Columns[4].GetCellContent(ViewOrdersGrid.Items[i]) as CheckBox;
                if (mycheckbox.IsChecked == true)
                {
                    MessageBox.Show("Checked");
                }

            }
        }

回答by Will Custode

You're already using MVVM, I can see by the bindings, so you're off to a good start. Now, because MVVM allows a very tight relationship between the UI and the data, we can inference that if we can traverse the visual tree for the checked property on a given object, we should also be able to traverse the data for such a property. So your C# code should look as follows (assuming in your code that DataGrid's ItemsSource is bound to a collection (lets call it MyItems):

您已经在使用 MVVM,我可以通过绑定看到,所以您有了一个良好的开端。现在,因为 MVVM 允许 UI 和数据之间的关系非常紧密,我们可以推断,如果我们可以遍历给定对象上的已检查属性的可视化树,我们也应该能够遍历此类属性的数据。因此,您的 C# 代码应如下所示(假设在您的代码中 DataGrid 的 ItemsSource 绑定到一个集合(我们称之为 MyItems):

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var viewModel = (ViewModelType)this.DataContext;

    foreach(var item in viewModel.MyItems)
    {
        if(item.BODelivered)
        {
            MessageBox.Show("Checked");
        }
    }
}

This example assumes that (because the rest of your example is using bindings appropriately) that your grid is bound to something (we called it MyItems). If you need to see how this works (meaning you haven't implemented it as MVVM and FOOLED ME) then consider the following:

这个例子假设(因为你的例子的其余部分正在适当地使用绑定)你的网格绑定到某个东西(我们称之为 MyItems)。如果您需要了解它是如何工作的(意味着您尚未将其实现为 MVVM 和FOOLED ME),请考虑以下事项:

This is your XAML

这是您的 XAML

<DataGrid CanUserAddRows="False" AutoGenerateColumns="False"
          CellEditEnding="SaveDeliveryValue" LoadingRow="DataGrid_LoadingRow"
          Name="ViewOrdersGrid" HorizontalAlignment="Center" Margin="0,10,0,0" 
          VerticalAlignment="Top" Height="278" Width="520" BorderBrush="#FFA0A0A0"
          ItemsSource="{Binding MyItems}">
    <DataGrid.Columns>
        <DataGridTextColumn  Header="Order No" Width="115" Binding="{Binding Path=BONo, Mode=OneWay}" />
        <DataGridTextColumn Header="Order Date" Width="100" Binding="{Binding Path=BODate, Mode=OneWay, StringFormat=d}" />
        <DataGridTextColumn Header="Total Amount" Width="100" Binding="{Binding Path=BOTotal, Mode=OneWay}" />
        <DataGridTextColumn Header="Total Bikes" Width="100" Binding="{Binding Path=BOTatalBikes, Mode=OneWay}" />
        <DataGridCheckBoxColumn Header="Delivered" x:Name="DeliveryValueCheck" Width="70" Binding="{Binding Path=BODelivered, Mode=TwoWay}" />
    </DataGrid.Columns>
</DataGrid>

This is your data structure

这是你的数据结构

public class MyObject
{
    public int BONo { get; set; }
    public DateTime BODate { get; set; }
    public int BOTotal { get; set; }
    public int BOTatalBikes { get; set; }
    public bool BODelivered { get; set; }
}

This is your *.xaml.cs file

这是您的 *.xaml.cs 文件

// this is the constructor for your view (MyWindow.xaml.cs)
private MyWindow( )
{
    this.DataContext = new MyViewModel( );
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    var viewModel = (ViewModelType)this.DataContext;

    foreach(var item in viewModel.MyItems)
    {
        if(item.BODelivered)
        {
            MessageBox.Show("Checked");
        }
    }
}

This is your view model (MyViewModel.cs)

这是您的视图模型 (MyViewModel.cs)

public class MyViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public void OnPropertyChanged(string property)
    {
        PropertyChanged(this, new PropertyChangedEventArgs(property));
    }

    private ObservableCollection<YourObjectTypeHere> _myItems;
    public ObservableCollection<YourObjectTypeHere> MyItems
    {
        get
        {
            return _myItems;
        }
        set
        {
            _myItems = value;
            OnPropertyChanged("MyItems");
        }
    }
}