Wpf工具包datagrid DataGridCheckBoxColumn on_click事件:

时间:2010-04-08 17:48:04

标签: wpf wpftoolkit

我想获取所选行,但是selecteditems只有一行。我想得到所有检查项目。我想我需要在选中复选框时添加事件处理程序,然后将它们全部收集起来。我该如何以最好的方式做到这一点?

1 个答案:

答案 0 :(得分:1)

您是否使用数据绑定来填充DataGrid?如果是这样,将列的已检查值绑定到后备对象中的bool可能是“最佳”(如:最佳实践)方式。以下是一些示例代码:

<Window x:Class="CheckGridSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:tk="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit"
    Title="Window1" Height="300" Width="300">
    <StackPanel>
        <tk:DataGrid ItemsSource="{Binding}" AutoGenerateColumns="False">
            <tk:DataGrid.Columns>
                <tk:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
                <tk:DataGridCheckBoxColumn Header="Selected" Binding="{Binding IsChecked}" />
            </tk:DataGrid.Columns>
        </tk:DataGrid>
        <Button Content="Which Items Are Checked?" Click="Button_Click" />
    </StackPanel>
</Window>

using System;
using System.Linq;
using System.Text;
using System.Windows;

namespace CheckGridSample
{
    public partial class Window1
    {
        public Window1()
        {
            InitializeComponent();
            DataContext = new[]
                {
                    new MyModel {Name = "Able"},
                    new MyModel {Name = "Baker", IsChecked = true},
                    new MyModel {Name = "Charlie"}
                };
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var builder = new StringBuilder();
            foreach (var item in ((MyModel[]) DataContext).Where(m => m.IsChecked))
                builder.Append(Environment.NewLine + item.Name);
            MessageBox.Show("Checked:" + builder);
        }
    }

    public class MyModel
    {
        public string Name { get; set; }
        public bool IsChecked { get; set; }
    }
}