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?
A:
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; }
}
}
Joseph Sturtevant
2010-04-08 17:55:08
@logu If you aren't using data binding, this is definitely the answer you are looking for. I would still look at my example, however, as I believe it is the "better" way to solve the problem you describe.
Joseph Sturtevant
2010-04-08 18:11:55
The following is my code. I want to collect all the selected rows in the code behind. How do I do that? I used wpf toolkit datagrid in wpfbrowser application. When I put binding for the check box, i can only select one. <my:DataGridCheckBoxColumn Header="Selected" Binding="{Binding IsChecked}" Thank you for you respond. appriciate any help???
logu
2010-04-08 18:52:48
<Page x:Class="Page1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Page1" Height="335" Width="524" xmlns:my="clr-namespace:Microsoft.Windows.Controls;assembly=WPFToolkit" Name="Page1"> <Grid> <my:DataGrid Margin="65,90,18,31" Name="DataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="False"> <my:DataGrid.Columns> <my:DataGridCheckBoxColumn Header="Include" /> </my:DataGrid.Columns> </my:DataGrid> </Grid></Page>
logu
2010-04-08 18:53:21