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

时间:2016-11-10 05:09:21

标签: c# wpf xaml mvvm datagrid

我想在一定的时间间隔后自动刷新数据网格。我使用的是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- 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秒刷新一次,并且只显示第一个记录。我希望每隔5秒以xml显示所有数据。如何实现这一目标?需要做哪些改变?

2 个答案:

答案 0 :(得分:1)

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

使用可观察的集合(如ObservableCollection)非常重要,否则View永远不会知道任何变化。

此应用程序每秒生成新数据。这些更改立即显示在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>

答案 1 :(得分:0)

您应该启用PropertyChanged。我假设你已经绑定了要查看的itemsField。我相信你的刷新工作正常。它只是没有反映出视野中的变化。

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;