首页 > 解决方案 > 如何通知源属性有关 Wpf DataGrid 中所做的更改?

问题描述

我有一个通过 Dependency 属性绑定到 Datatable 的 Datagrid。即使我将绑定模式设置为两种方式,我也无法检索我在数据网格中所做的更改。

编辑 dataGrid 时,将更改更新回 Source DataTable 的最佳方法是什么?

我知道我可以使用 DataAdapter.Update() 来提交对数据库的更改,但这不是我要问的,所以不要混淆。我想知道将更改保存回 ViewModel 的 DataTable 属性的有效方法。

Datatable 属性在运行时填充为:

class EmployeeViewModel : INotifyPropertyChanged
{



    private DataTable _dt = new DataTable();

    public event PropertyChangedEventHandler PropertyChanged;
    
    public DataTable _Table
    {
        get
        {
            return _dt;
        }
        set
        {
            _dt = value;
            OnPropertyChanges(nameof(_Table));
        }
    }

    private void OnPropertyChanges(String propertyName)
    {

        var h = PropertyChanged;
        if (h != null)
            h(this, new PropertyChangedEventArgs(propertyName));
        //   PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
    }

    public EmployeeViewModel()
    {
        
        ReadData();
    }

    

   
    public void ReadData()
    {

        string cs = ConfigurationManager.ConnectionStrings["Employee.mdf"].ConnectionString;
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlDataAdapter da = new SqlDataAdapter("Select * from tblStudents", con);
            DataSet set = new DataSet();
            da.Fill(set, "Students");
            _Table = set.Tables[0];

        }
    }
}

名为 StudentsGrid 的自定义用户控件只是网格内的数据网格:

<UserControl x:Class="ADO.Net_Practice.StudentsGrid"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:ADO.Net_Practice"
         mc:Ignorable="d" 
         d:DesignHeight="450" d:DesignWidth="800">
<Grid>
    <DataGrid ItemsSource="{Binding StudentsTable, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:StudentsGrid}}, Mode=TwoWay}" Margin="10,10,0,0" HorizontalAlignment="Center" VerticalAlignment="Top" MinHeight="200"/>            
</Grid>

这是上面 xaml 的代码隐藏,其中注册了依赖属性:


    /// <summary>
    /// Interaction logic for StudentsGrid.xaml
    /// </summary>
    public partial class StudentsGrid : UserControl
    {
        public StudentsGrid()
        {
            InitializeComponent();
        }



        public DataTable StudentsTable
        {
            get { return (DataTable)GetValue(StudentsTableProperty); }
            set { SetValue(StudentsTableProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StudentsTable.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StudentsTableProperty =
            DependencyProperty.Register("StudentsTable", typeof(DataTable), typeof(StudentsGrid), new PropertyMetadata(new DataTable(), StudentsTablePropertyChanged));

        private bool _updating;

        private static void StudentsTablePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var st = d as StudentsGrid;
            if(st!=null)
            {
                st.DataChanged();
            }
        }

        private void DataChanged()
        {
            if (_updating)
                return;
            _updating = true;
            
            _updating = false;
        }
    }

最后一个是将 StudentTable 属性绑定到自定义用户控件的 MainWindow:

<Grid>
        
        <local:StudentsGrid StudentsTable="{Binding _Table, Mode=TwoWay}"/>

</Grid>

mainWindow 的数据上下文在代码隐藏的构造函数中设置为:

 DataContext = new EmployeeViewModel();

这是我得到的结果: 从数据库填充的数据网格

标签: wpfmvvmdatatabledatagriddependency-properties

解决方案


推荐阅读