logu
logu

Reputation: 11

Wpf tool kit datagrid DataGridCheckBoxColumn on_click event:

I want to get the selected rows, but selecteditems has only one row. I want get the all the checked item. I think I need to add event handler when the checkbox is clecked and then collect them all. How do I do this in a best way?

Upvotes: 1

Views: 4411

Answers (1)

Joseph Sturtevant
Joseph Sturtevant

Reputation: 13360

Are you using databinding to populate your DataGrid? If so, binding the checked value of your column to a bool in your backing object is probably the "best" (as in: best-practices) way to do this. Here is some example code:

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

Upvotes: 1

Related Questions