C# 更改文本框文本时自动更改DataGrid中的数据(Xml源)

C# 更改文本框文本时自动更改DataGrid中的数据(Xml源),c#,xml,wpf,C#,Xml,Wpf,我对编程相当陌生,我正在用C#和WPF创建一个小的客户管理应用程序。 在我的代码中,我使用DataGrid来显示XML文件中的数据。 我的问题是,当我更改特定单元格的TextBox文本时,我希望DataGrid中的数据同时更改,我考虑在TextBox上使用TextChanged事件,但我不知道如何管理其余部分 (代码并不完美,目前并非所有内容都能完美运行) 代码隐藏: using System; using System.Collections.Generic; using System.Dat

我对编程相当陌生,我正在用C#和WPF创建一个小的客户管理应用程序。 在我的代码中,我使用
DataGrid
来显示XML文件中的数据。 我的问题是,当我更改特定单元格的
TextBox
文本时,我希望
DataGrid
中的数据同时更改,我考虑在
TextBox
上使用
TextChanged
事件,但我不知道如何管理其余部分

(代码并不完美,目前并非所有内容都能完美运行)

代码隐藏:

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.Xml;

namespace Kunden2
{
    public partial class MainWindow : Window
    {
        List<Customer> customerlist = new List<Customer>();
        public int RowNumber;

        public MainWindow()
        {
            InitializeComponent();
            if (TextBoxListe.Text.Length != 0)
            {
                ShowList(TextBoxListe.Text + ".xml");
            }

            RowCount();
        }

        //Button Refresh
        private void ButtonRefresh_Click(object sender, RoutedEventArgs e)
        {
            ShowList(TextBoxListe.Text + ".xml");
        }

        //Button Add
        private void ButtonAdd_Click(object sender, RoutedEventArgs e)
        {
            AddPerson();
        }

        //Button Save
        private void ButtonSave_Click(object sender, RoutedEventArgs e)
        {
            SaveXML();
            MessageBox.Show("Erfolgreich gespeichert.");
        }


        //Show List
        private void ShowList(string list)
        {
            if (TextBoxListe.Text.Length != 0)
            {
                if (File.Exists(TextBoxListe.Text + ".xml"))
                {
                    XmlSerializer serial = new XmlSerializer(typeof(List<Customer>));
                    using (FileStream stream = new FileStream(Environment.CurrentDirectory + "/" + list, FileMode.Open, FileAccess.Read))
                    {
                        customerlist = ((List<Customer>)serial.Deserialize(stream));
                    }
                    DataGrid.ItemsSource = customerlist;
                }
                else
                {
                    MessageBox.Show("Datei existiert nicht!");
                }
            }
            else
            {
                MessageBox.Show("Bitte eine Liste eingeben");
            }
            TextBoxNummer.Text = "";
        }


        //Selection to TextBox
        private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            object item = DataGrid.SelectedItem;
            if (item == null)
            {
                TextBoxName.Text = "";
                TextBoxLastName.Text = "";
                TextBoxFirma.Text = "";
                return;
            }

            string Nummer = (DataGrid.SelectedCells[0].Column.GetCellContent(item) as TextBlock).Text;
            string Name = (DataGrid.SelectedCells[1].Column.GetCellContent(item) as TextBlock).Text;
            string NachName = (DataGrid.SelectedCells[2].Column.GetCellContent(item) as TextBlock).Text;
            string Firma = (DataGrid.SelectedCells[3].Column.GetCellContent(item) as TextBlock).Text;

            TextBoxNummer.Text = Nummer;
            TextBoxName.Text = Name;
            TextBoxLastName.Text = NachName;
            TextBoxFirma.Text = Firma;
        }

        //Add Person
        private void AddPerson()
        {
            RowNumber++;
            customerlist.Add(new Customer() { NachName = TextBoxLastName.Text, Name = TextBoxName.Text, Firma = TextBoxFirma.Text, KundenNummer = RowNumber, Aktiv = true });
            updateDataGrid();
            TextBoxNummer.Text = "";
            TextBoxName.Text = string.Empty;
            TextBoxLastName.Text = string.Empty;
            TextBoxFirma.Text = string.Empty;
        }

        //Update Data
        private void updateDataGrid()
        {
            DataGrid.ItemsSource = null;
            DataGrid.ItemsSource = customerlist;
        }

        //Save to XML
        private void SaveXML()
        {
            if (TextBoxName.Text.Length == 0 && TextBoxLastName.Text.Length == 0 && TextBoxFirma.Text.Length == 0)
            {
                XmlSerializer serial = new XmlSerializer(typeof(List<Customer>));
                using (FileStream stream = new FileStream(Environment.CurrentDirectory + "/" + TextBoxListe.Text + ".xml", FileMode.Create, FileAccess.Write))
                {
                    serial.Serialize(stream, customerlist);
                }
            }
            else
            {
                XmlSerializer serial = new XmlSerializer(typeof(List<Customer>));
                using (FileStream stream = new FileStream(Environment.CurrentDirectory + "/" + TextBoxListe.Text + ".xml", FileMode.Create, FileAccess.Write))
                {
                    serial.Serialize(stream, customerlist);
                }
            }
        }

        //Button Delete
        private void ButtonLöschen_Click(object sender, RoutedEventArgs e)
        {
            XmlDocument xdoc = new XmlDocument();
            FileStream up = new FileStream(TextBoxListe.Text + ".xml", FileMode.Open);
            xdoc.Load(up);
            XmlNodeList list = xdoc.GetElementsByTagName("Customer");
            for (int i = 0; i < list.Count; i++)
            {
                XmlElement cu = (XmlElement)xdoc.GetElementsByTagName("Customer")[i];

                if (cu.GetAttribute("KundenNummer") == TextBoxNummer.Text)
                {
                    cu.SetAttribute("Aktiv", "false");

                    break;
                }
            }
            up.Close();
            xdoc.Save(TextBoxListe.Text + ".xml");
            ShowList(TextBoxListe.Text + ".xml");
        }

        private void RowCount()
        {
            RowNumber = customerlist.Count();
        }

        //Button Open
        private void ButtonOpen_Click(object sender, RoutedEventArgs e)
        {
            ShowList(TextBoxListe.Text + ".xml");

        }

        //Text Changed Event
        private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
        {
            // What to do here to update the "Name"?
        }
    }
}


由于您使用的是纯代码隐藏,因此我将向您展示一个解决方案,尽管我建议您熟悉MVVM设计模式,它可以通过绑定将您从大量事件处理中解救出来,并允许将表示、逻辑和数据完全分离

要更新文本更改事件处理程序中的数据,您需要访问
DataGrid
中的
SelectedItem
,并将其相应属性设置为相关
文本框的
text

private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
{
   if (DataGrid.SelectedItem is Customer customer)
      customer.Name = ((TextBox)sender).Text;
}
但是,此更改尚未反映在用户界面中,因为您的
客户
模型没有实现。您可以像下面那样为所有属性实现它。它所做的是在属性被修改时引发属性的
PropertyChanged
事件,以表示控件必须更新其绑定以获得更改的值

public class Customer : INotifyPropertyChanged
{
   private string _name;
   public string Name
   {
      get => _name;
      set
      {
         if (_name != value)
         {
            _name = value;
            OnPropertyChanged();
         }
      }
   }

   // ...your other properties.

   public event PropertyChangedEventHandler PropertyChanged;

   protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
   {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
}

谢谢你的盛情款待。这对我很有效。
private void TextBoxName_TextChanged(object sender, TextChangedEventArgs e)
{
   if (DataGrid.SelectedItem is Customer customer)
      customer.Name = ((TextBox)sender).Text;
}
public class Customer : INotifyPropertyChanged
{
   private string _name;
   public string Name
   {
      get => _name;
      set
      {
         if (_name != value)
         {
            _name = value;
            OnPropertyChanged();
         }
      }
   }

   // ...your other properties.

   public event PropertyChangedEventHandler PropertyChanged;

   protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
   {
      PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
   }
}