[英]fetch selected row from DataGrid
我正在使用WPF网格。 第一列是CheckBox列,我的页面上有一个保存按钮。 单击该按钮后,我希望选中所有复选框行,然后在数据表中插入。
如何才能做到这一点?
这样的帮助吗?
它使用装饰器模式包装类(可能来自LINQ2SQL之类的ORM),以使您能够对“选定”值进行数据绑定。 然后,您可以在保存时在装饰项目列表中查找所选项目,然后仅保存这些项目。
(简单示例,不符合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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.