Quantcast
Channel: WPF datagrid
Viewing all articles
Browse latest Browse all 3

WPF datagrid

$
0
0

Hi,

Try the below.

<Window x:Class="DatagridLazy_Learning.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"><Grid><DataGrid x:Name="dgr"></DataGrid></Grid></Window>

public partial class MainWindow : Window
    {
        public ObservableCollection<Person> Persons { get; set; }

        private object _personLock = new object();

        public MainWindow()
        {
            InitializeComponent();

            Persons = new ObservableCollection<Person>();
            BindingOperations.EnableCollectionSynchronization(Persons, _personLock);
            dgr.ItemsSource = Persons;
            StartAddingItems();
        } 
        private Random _random = new Random();
        public void AddNewItems()
        {
            for (int i = 0; i < 100; i++)
            {
                var obj = new Person();
                obj.Name = "Person" + i.ToString();
                Persons.Add(obj);
            }
        }
        public void StartAddingItems()
        {
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    AddNewItems();
                    Thread.Sleep(500);
                }
            });
        }
    }

    public class Person : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private string _name;

        public string Name
        {
            get { return _name; }
            set { _name = value; NotifyPropertyChanged("Name"); }
        }
        private int _age;

        public int Age
        {
            get { return _age; }
            set { _age = value; NotifyPropertyChanged("Age"); }
        }

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

Reference:http://10rem.net/blog/2012/01/16/wpf-45-observable-collection-cross-thread-change-notification


Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>