WPF数据网格与MVVM [英] WPF datagrid with MVVM

查看:106
本文介绍了WPF数据网格与MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在WPF中DataGrid绑定到我的视图模型,以便它将更新任何细胞变化到数据库,并允许用户删除行和添加新行。我得到了它的工作的一部分,但无法找到该添加优雅的解决方案和修改。这里
是XAML

I'm trying to bind a datagrid in WPF to my ViewModel so that it will update any cell changes to the database as well as allow the user to delete rows and add new rows. I've got part of it working but can't find a ELEGANT solution for the ADD and modify. here is the xaml

<DataGrid AutoGenerateColumns="false" 
              ItemsSource="{Binding Path=GetAllItems}" Height="200" 
              HorizontalAlignment="Left" 
              Margin="26,41,0,0" Name="dataGrid1" 
              VerticalAlignment="Top" Width="266" >
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding Path=ItemListID}" Header="ID" Visibility="Hidden"/>
                <DataGridTextColumn Binding="{Binding Path=ItemName}" Header="Name" Width="4*" />
                <DataGridCheckBoxColumn Binding="{Binding Path=IsActive}" Header="Active" Width="*"  />
               </DataGrid.Columns>



在我看来,模型方法,那么

then in my view model method

  private ObservableCollection< ItemsList> getAllItems()
    {
        using (var context = new InspectorGeneralEntities())
        {
            var query = from I in context.ItemsLists
                        select I;
            var item = new ObservableCollection<ItemsList>(query.ToList());
            return item;
        }
    }



删除行或在数据网格修改排不没有流到数据库。

Deleting a row or modifying a row on the datagrid does not flow onto the database.

一)我需要什么其他具有约束力的XAML代码,将检测这些事件

a) what other binding do i need to create in the xaml code that will detect these events

二)我怎样检测视图模型中的记录删除或修改项目,这样我可以更新DataContext的,如果它不会自动

b) How do i detect a removed record or modified item in the view model so that I can update the datacontext if it won't automatically.

推荐答案

我看到一对夫妇的问题,在你的问题中的代码。但是,为什么删除行不会反映在数据库中的原因是的 .ToList()的 - 基本上你创建一个新的列表,它是一个副本的查询的和网格删除从该副本的元素。

I see a couple of problems with the code in your question. But the reason why deleting a row is not reflected in the database is the .ToList() -- essentially you're creating a new list which is a copy of query and the grid is removing elements from that copy.

您应该使用的ListCollectionView ,并使用过滤器代替。LINQ声明

You should use a ListCollectionView and use a Filter instead of a linq statement.

下面是展示如何做到这一点的例子:

Here's a sample showing how to do it:

1)创建一个新的WPF项目,称为的 ListCollectionViewTest

1) Create a new WPF project called ListCollectionViewTest

2)在MainWindow.xaml.cs剪切和放大器;粘贴下面的(应该是在视图模型,但我太懒)

2) In the MainWindow.xaml.cs cut&paste the following (should be in ViewModel but I'm too lazy)

    using System.Collections.Generic;
    using System.Linq;
    using System.Windows;
    using System.Windows.Data;

    namespace ListCollectionViewTest
    {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
        {
            private List<Employee> equivalentOfDatabase = new List<Employee>()
                        {
                            new Employee() { FirstName = "John", LastName = "Doe", IsWorthyOfAttention = true },
                            new Employee() { FirstName = "Jane", LastName = "Doe", IsWorthyOfAttention = true },
                            new Employee() { FirstName = "Mr.", LastName = "Unsignificant", IsWorthyOfAttention = false },
                        };

            public ListCollectionView TestList { get; set; }
            public MainWindow()
            {
                DataContext = this;

                // This is all the magic you need -------
                TestList = new ListCollectionView(equivalentOfDatabase);
                TestList.Filter = x => (x as Employee).IsWorthyOfAttention;

                InitializeComponent();
            }

            private void Button_Click(object sender, RoutedEventArgs e)
            {
                MessageBox.Show(equivalentOfDatabase.Aggregate("Employees are: \n\r", (acc, emp) => acc + string.Format("    - {0} {1}\n\r", emp.FirstName, emp.LastName), x => x));
            }
        }

        public class Employee
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool IsWorthyOfAttention { get; set; }
        }
    }



3)在MainWindow.xaml剪切和放大器;粘贴此

3) In MainWindow.xaml cut&paste this:

    <Window x:Class="ListCollectionViewTest.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">

        <StackPanel>
            <DataGrid ItemsSource="{Binding TestList}"
                      RowHeight="22"
                      AutoGenerateColumns="True">
            </DataGrid>
            <Button Content="Show All Employees in DB" Click="Button_Click" />
        </StackPanel>        
    </Window>

这篇关于WPF数据网格与MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆