I'm using WPF Grid. The first column is a CheckBox column, and there is one save button on my page. When the button is clicked, I'd like all the checkboxes row to be set checked, insert a in a datatable.
How can this be done?
I'm using WPF Grid. The first column is a CheckBox column, and there is one save button on my page. When the button is clicked, I'd like all the checkboxes row to be set checked, insert a in a datatable.
How can this be done?
Would something like this help?
It uses a decorator pattern to wrap a class (that's probably come out of an ORM like LINQ2SQL) to enable you to databind a "selected" value. You can then upon saving look for selected items in the list of decorated items and save only those.
(Simple example, not MVVM compliant)
XAML:
<Window x:Class="CheckTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" ItemsSource="{Binding Path=Foos}" Name="gridFoos" Margin="0,0,0,34">
<DataGrid.Columns>
<DataGridCheckBoxColumn Header="Selected" Binding="{Binding Path=Selected}"/>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Value.Name}" />
<DataGridTextColumn Header="Age" Binding="{Binding Path=Value.Age}"/>
</DataGrid.Columns>
</DataGrid>
<Button Content="Save" Height="23" HorizontalAlignment="Left" Margin="423,283,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="btnSave_Click" />
</Grid>
</Window>
Code behind:
namespace CheckTest
{
public partial class MainWindow : Window
{
public ObservableCollection<SelectedDecorator<Foo>> Foos { get; set; }
public MainWindow()
{
var bars = new List<Foo>() { new Foo() { Name = "Bob", Age = 29 }, new Foo() { Name = "Anne", Age = 49 } };
var selectableBars = bars.Select(_ => new SelectedDecorator<Foo>(_)).ToList();
Foos = new ObservableCollection<SelectedDecorator<Foo>>(selectableBars);
InitializeComponent();
DataContext = this;
}
private void btnSave_Click(object sender, RoutedEventArgs e)
{
var saveThese = Foos.ToList().Where(_ => _.Selected).Select(_=> _.Value);
//db.BulkUpdate(saveThese); ... or some sutch;
}
}
public class Foo
{
public string Name{get;set;}
public int Age { get; set; }
}
public class SelectedDecorator<T>
{
public T Value { get; set; }
public bool Selected { get; set; }
public SelectedDecorator(T value)
{
Selected = false;
this.Value = value;
}
}
}