簡體   English   中英

如何自動更新 WPF DataGrid 和 xml 之間的綁定

[英]How to automatically update Binding between WPF DataGrid and xml

我有一個 xml 文件並與 WPF DataGrid 綁定。 我還有一種方法可以更新 xml 文件。 但編輯 xml 后,DataGrid 不會自動更新。 是否可以升級 DataGrid?

這是 xaml 代碼:

        <Window x:Class="TestWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:TestWPF"
        mc:Ignorable="d"
        Title="MainWindow" Height="600" Width="750" Name ="Window" >
    <Grid Margin="-16,-34,-8,-96">

        <DataGrid x:Name="Dgr_Archive" HorizontalAlignment="Left" Height="215" Margin="25,375,0,0" VerticalAlignment="Top" Width="725"
                  ItemsSource="{Binding}"  AutoGenerateColumns="False" GridLinesVisibility="Horizontal">
            <DataGrid.DataContext>
                <XmlDataProvider Source="C:\Users\1\source\repos\TestWPF\TestWPF\Archive.xml" XPath="/Companies/Company" />
            </DataGrid.DataContext>
            
            <DataGrid.Columns >
                <DataGridTextColumn Width="25" Header="ID" Binding="{Binding XPath=@id}">
                <DataGridTextColumn Width="110" Header="Company Name" Binding="{Binding XPath=@name}"/>
                <DataGridTextColumn Width="110" Header="Position" Binding="{Binding XPath=Position}"/>
                <DataGridTextColumn Width="110" Header="Address" Binding="{Binding XPath=Address}"/>
                <DataGridTextColumn Width="110" Header="E mail" Binding="{Binding XPath=E_mail}"/>
                <DataGridTextColumn Width="119" Header="Contact person" Binding="{Binding Path=Contact_person}"/>
                <DataGridTextColumn Width="116" Header="Record Timestamp" Binding="{Binding XPath=Record_Timestamp}"/>
        </DataGrid>
        

    </Grid>
</Window>

這里是代碼方法 C# 添加記錄到 xml

        private void Add_record(XDocument doc)
        {
            XElement n = doc.Root.LastNode as XElement;
            Int32.TryParse(n.Attribute("id").Value, out int LastElementID);

            doc.Root.Add(new XElement("Company",
                       new XElement("Position", Tbx_Position.Text),
                       new XElement("Address", Tbx_Address.Text + "  " + Tbx_PLZOrt.Text),
                       new XElement("E_mail", Tbx_Email.Text),
                       new XElement("Contact_person", Tbx_Person.Text),
                       new XElement("Record_Timestamp", DateTime.Now.ToString()),
                       new XAttribute("name", Tbx_Company_Name.Text.Replace(" ", "_")),
                       new XAttribute("id", (LastElementID + 1))));
            doc.Save(archpath);

我正在為我的所有實體(您在 ItemsSource 中的行項目)使用下面的 class。

using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace eTabber.Data.Model
{
    public class PropertyChangedEntity : INotifyPropertyChanged
    {
        public void NotifyPropertyChangedRefType<TValue>(ref TValue oldValue, TValue newValue, [CallerMemberName] string name = null)
            where TValue : class
        {
            if (string.IsNullOrEmpty(name)) throw new InvalidOperationException("Name cannot be null!");

            if (oldValue == null)
            {
                if (newValue != null && !newValue.Equals(oldValue))
                {
                    SetAndNotify(ref oldValue, newValue, name);
                }
            }
            else
            {
                if (!oldValue.Equals(newValue))
                {
                    SetAndNotify(ref oldValue, newValue, name);
                }
            }
        }

        private void SetAndNotify<TValue>(ref TValue oldValue, TValue newValue, string name) where TValue : class
        {
            oldValue = newValue;
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }

        public void NotifyPropertyChangedValueType<TValue>(ref TValue oldValue, TValue newValue, [CallerMemberName] string name = null)
        {
            if (string.IsNullOrEmpty(name)) throw new InvalidOperationException("Name cannot be null!");

            if (!newValue.Equals(oldValue))
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
            }

            oldValue = newValue;
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }
}

並且可以在您的派生類中像這樣使用它:

public class Account : PropertyChangedEntity
{
    ... 

    DateTime _ModificationsTimestamp;
    /// <summary>
    /// Timestamp for modifications
    /// </summary>
    public DateTime ModificationsTimestamp { get => _ModificationsTimestamp; set => NotifyPropertyChangedValueType(ref _ModificationsTimestamp, value); }

    private HashSet<SetList> _SetLists;

    /// <summary>
    /// Setlistst belonging to this account
    /// </summary>
    public HashSet<SetList> SetLists { get => _SetLists; set => NotifyPropertyChangedRefType(ref _SetLists, value); }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM