WPF数据网格在一段时间间隔后不会自动刷新

本文关键字:刷新 数据网 数据 网格 一段时间 WPF | 更新日期: 2023-09-27 18:17:17

我想在一定时间间隔后自动刷新数据网格。我使用MVVM模型。

添加模型- EmployeeDetails.cs

namespace AutoRefresh3.Model
{
   public class EmployeeDetails
    {
        private string name;
        private string location;
        private double salary;
        [System.Xml.Serialization.XmlElementAttribute("Name")]
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                this.name = value;
                NotifyPropertyChanged("Name");
            }
        }
        [System.Xml.Serialization.XmlElementAttribute("Location")]
        public string Location
        {
            get
            {
                return location;
            }
            set
            {
                this.location = value;
                NotifyPropertyChanged("Location");
            }
        }
        [System.Xml.Serialization.XmlElementAttribute("Salary")]
        public double Salary
        {
            get
            {
                return salary;
            }
            set
            {
                this.salary = value;
                NotifyPropertyChanged("Salary");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

}

添加ViewModel - EmployeeViewModel.cs

namespace AutoRefresh3.ViewModel
{
    class EmployeeViewModel
    {
        private ObservableCollection<EmployeeDetails> empdetails = new ObservableCollection<EmployeeDetails>();
        [System.Xml.Serialization.XmlElementAttribute("EmpDetails")]
        public ObservableCollection<EmployeeDetails> EmpDetails
        {
            get
            {
                return empdetails;
            }
            set
            {
                value = empdetails;
                NotifyPropertyChanged("EmpDetails");
            }
        }
        public void LoadEmployees()
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(EmployeeDetails));
            TextReader reader = new StreamReader(@"C:'xlf'employeedetails1.xml");
            object obj = deserializer.Deserialize(reader);
            EmployeeDetails ed = (EmployeeDetails)obj;
            empdetails.Add(ed);

            //EMPDetails empdetails = (EMPDetails)obj;
            //employees.Add(emp);
            //employees = (EmployeeDetails)empdetails;
        }
        public void setTimer()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(5000);
            timer.Tick += Timer_Tick;
            timer.Start();
        }
        private void Timer_Tick(object sender, System.EventArgs e)
        {
            LoadEmployees();
        }

        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(String propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

添加视图- View .xaml

<Window x:Class="AutoRefresh3.View.view"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="view" Height="300" Width="300">
    <Grid>
        <DataGrid  HorizontalAlignment="Left"  x:Name="datagrid1" AutoGenerateColumns="False"
                   ItemsSource="{Binding EmpDetails}" 
                   Height="600" Margin="24,79,0,0" VerticalAlignment="Top" Width="600">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Employee Name" Binding="{Binding Name}" />
                <DataGridTextColumn Header="Employee Location" Binding="{Binding Location}"/>
                <DataGridTextColumn Header="Employee Salary" Binding="{Binding Salary}"/>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

view.xaml.cs

namespace AutoRefresh3.View
{
    /// <summary>
    /// Interaction logic for view.xaml
    /// </summary>
    public partial class view : Window
    {
        public view()
        {
            InitializeComponent();
            EmployeeViewModel ed = new EmployeeViewModel();
            this.DataContext = ed;
            ed.LoadEmployees();
            ed.setTimer();
        }
    }
}

employeedetails1.xml

<?xml version="1.0" ?> 
<EmployeeDetails>

<Name>abc</Name>
<Location>Bangalore</Location>
<Salary>1000000</Salary>

<Name>def</Name>
<Location>Mysore</Location>
<Salary>2000000</Salary>

<Name>ghi</Name>
<Location>USA</Location>
<Salary>50000</Salary>
</EmployeeDetails>

上面的项目只能在数据网格中显示第一个员工信息,每5秒刷新一次,只显示第一个记录。我想显示所有的数据在xml每5秒..如何做到这一点?需要做哪些改变?

WPF数据网格在一段时间间隔后不会自动刷新

我希望这是你正在寻找的行为。

使用一个可观察的集合(如ObservableCollection)是很重要的,否则视图永远不会知道任何改变。

此应用程序每秒生成新数据。更改会立即显示在DataGrid中。

代码后面

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
}
public partial class MainWindow : Window
{
    public ObservableCollection<Employee> Employees { get; set; }
    public MainWindow()
    {
        InitializeComponent();
        Employees = new ObservableCollection<Employee>();
        datagrid1.DataContext = this;
        DispatcherTimer timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(200);
        timer.Tick += Timer_Tick;
        timer.Start();
    }
    private void Timer_Tick(object sender, System.EventArgs e)
    {
        Employees.Add(new Employee
        {
            Name = "Name",
            Age = (new Random()).Next(0, 100)
        });
    }
}

XAML

    <DataGrid HorizontalAlignment="Left" x:Name="datagrid1" 
               AutoGenerateColumns="False" ItemsSource="{Binding Employees}">
        <DataGrid.Columns>
            <DataGridTemplateColumn Header="Name">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Name}"></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTemplateColumn Header="Age">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Age}"></TextBlock>
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
    </DataGrid>

您应该启用PropertyChanged。我假设您已经将itemsField绑定到view。我相信你的提神效果不错。它只是没有反映视图的变化。

Object_Type itemsField {
   set {
       this._itemsField = value;
       onPropertyChanged("itemsField");
       }
   get{
       return this._itemsField;
       }
    }
void OnPropertyChanged(string prop)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
        public event PropertyChangedEventHandler PropertyChanged;