我正在使用WPF网格。第一列是CheckBox列,我的页面上有一个保存按钮。单击该按钮时,我希望选中所有复选框行,然后在数据表中插入一个。
如何做到这一点?
答案 0 :(得分:0)
这样的事情有帮助吗?
它使用装饰器模式来包装一个类(可能来自ORM,如LINQ2SQL),使您能够对“选定”值进行数据绑定。然后,您可以在保存中查找装饰项列表中的选定项目,并仅保存这些项目。
(简单示例,不符合MVVM)
<强> 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>
代码背后:
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;
}
}
}