使用自动刷新将ObservableCollection绑定到DataGrid

时间:2016-06-29 13:56:59

标签: c# wpf datagrid

我正在尝试将ObservableCollection列表绑定到数据网格。

列表中的值每100毫秒更改一次。 我希望如果值发生变化,网格会自动刷新。

这是一个让它工作的小型演示项目。但没有刷新UI按钮,一切正常。

public partial class MainWindow : Window
{
    public ObservableCollection<DemoItem> ItemList = new ObservableCollection<DemoItem>(); 

    public MainWindow()
    {
        InitializeComponent();

        DemoItem di1 = new DemoItem();
        di1.Name = "Spieler 1";
        di1.Zufallszahl = 0;
        di1.Alter = 21;

        DemoItem di2 = new DemoItem();
        di2.Name = "Spieler 2";
        di2.Zufallszahl = 0;
        di2.Alter = 15;

        ItemList.Add(di1);
        ItemList.Add(di2);

        DispatcherTimer dt = new DispatcherTimer();
        dt.Interval = new TimeSpan(0, 0, 0, 0, 100);
        dt.Tick += Dt_Tick;
        dt.Start();
    }

    public ObservableCollection<DemoItem> ObservableDemoItem
    {
        get
        {
            return this.ItemList;
        }
    }

    private void Dt_Tick(object sender, EventArgs e)
    {
        Random rnd = new Random();

        ItemList[0].Zufallszahl = rnd.Next(0, 1000);
        ItemList[1].Zufallszahl = rnd.Next(0, 1000);
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        dataGrid.Items.Refresh();
    }
}

XAML:

<Window x:Class="WpfApplication1.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:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="359.428" Width="539.141">
<Grid>
    <DataGrid x:Name="dataGrid" HorizontalAlignment="Left" 
        Margin="10,10,0,0" SelectionMode="Extended" VerticalAlignment="Top"
        Height="199" Width="497" CanUserAddRows="False" 
        CanUserDeleteRows="False" AutoGenerateColumns="False" 
        DataContext="{Binding RelativeSource={RelativeSource AncestorType=Window}}" 
        ItemsSource="{Binding ObservableDemoItem}" >
        <DataGrid.Columns>
            <DataGridTextColumn Header="Name" Binding="{Binding Name}" />
            <DataGridTextColumn Header="Alter" Binding="{Binding Alter}" />
            <DataGridTextColumn Header="Aktiv" Binding="{Binding Zufallszahl}" />
        </DataGrid.Columns>
    </DataGrid>
    <Button x:Name="button1" Content="Update UI" HorizontalAlignment="Left" 
        Margin="55,245,0,0" VerticalAlignment="Top" 
        Width="425" Height="61" Click="button1_Click"/>
</Grid>
</Window>

我需要改变什么才能使其发挥作用?

2 个答案:

答案 0 :(得分:3)

ObservableCollection仅在已添加或删除元素时通知UI有关更改(引发CollectionChanged事件),而不是在现有元素已更改的情况下。

要跟踪集合中元素的变化,例如建议的Nitro.deEd Plunkett,元素的类应实现INotifyPropertyChanged接口,如下所示:

using System.ComponentModel;
public class DemoItem : INotifyPropertyChanged
{
    private int _age;
    private int _score;
    private string _name;

    public int Age
    {
        get { return _age; }
        set { if (_age != value) { _age = value; OnPropertyChanged("Age"); } }
    }
    public int Score
    {
        get { return _score; }
        set { if (_score != value) { _score = value; OnPropertyChanged("Score"); } }
    }
    public string Name
    {
        get { return _name; }
        set { if (_name != value) { _name = value; OnPropertyChanged("Name"); } }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

答案 1 :(得分:-2)

假设您的集合每100毫秒发生显着变化,我会尝试从集合中发送重置通知,以便DataGrid知道需要刷新数据。 您需要创建一个ObservableCollection派生类,包含与此类似的方法

public void NotifyOnReset()
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
}

并在需要时调用它。

P.S。确保在UI线程上调用此方法,或采用其他同步方法。