【问题标题】:fetch selected row from DataGrid从 DataGrid 中获取选定的行
【发布时间】:2010-09-22 05:28:36
【问题描述】:

我正在使用 WPF 网格。第一列是 CheckBox 列,我的页面上有一个保存按钮。单击按钮时,我希望将所有复选框行设置为选中,在数据表中插入一个。

如何做到这一点?

【问题讨论】:

  • 你能提供一些代码作为例子吗?

标签: c# wpf datagrid


【解决方案1】:

这样的东西会有帮助吗?

它使用装饰器模式来包装一个类(这可能来自像 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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-11-22
    • 2012-11-11
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2011-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多