我有以下风景:
1 using System;
2 using System.Windows;
3 using System.Windows.Controls;
4 using System.Windows.Documents;
5 using System.Windows.Ink;
6 using System.Windows.Input;
7 using System.Windows.Media;
8 using System.Windows.Media.Animation;
9 using System.Windows.Shapes;
10 using System.Collections.Generic;
11
12 namespace refresh
13 {
14 public partial class MainPage : UserControl
15 {
16
17 List c = new List();
18
19 public MainPage()
20 {
21 // Required to initialize variables
22 InitializeComponent();
23 c.Add(new Customer{ _nome = "Josimari", _idade = "29"});
24 c.Add(new Customer{_nome = "Wesley", _idade = "26"});
25 c.Add(new Customer{_nome = "Renato",_idade = "31"});
26
27 this.dtGrid.ItemsSource = c;
28 }
29
30 private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
31 {
32 c.Add(new Customer{_nome = "Maiara",_idade = "18"});
33 }
34
35 }
36
37 public class Customer
38 {
39 public string _nome{get; set;}
40 public string _idade{get; set;}
41 }
42 }
其中,dtGrid是我的DataGrid控件......
问题是:如何在我的列表中再添加一个寄存器后更新UI。
我得解决它将DataGrid的Item Source设置为“”,然后再次设置为Customer对象列表,如下所示:
1 private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
2
3 {
4
5 c.Add(new Customer{_nome = "Maiara",_idade = "18"});
6
7 this.dtGrid.ItemsSource="";
8
9 this.dtGrid.ItemsSource=c;
10
11 }
12
在更新,更改或删除列表中的项目后,有没有办法让UI更新或datagrid的itemsSource自动刷新?
谢谢,
Josimari Martarelli
答案 0 :(得分:8)
我建议查看绑定,INotifyPropertyChanged,DataContexts和ObservableCollection。
将您的List
更改为ObservableCollection
。仅此一点可能会解决您的一些问题......因为ObservableCollection
比简单List
但是,如果你想解决更多类似的问题,你会考虑通过Xaml DataGrid
<DataGrid... ItemsSource="{Binding MyList}">
绑定到对象列表
要将DataGrid
绑定到List
,您需要设置视图的DataContext
。放置在构造函数中可以很简单:this.DataContext = this;
设置DataContext
告诉视图在查看Binding
语句时查找数据的位置
然后,为了解决您所拥有的问题(更改某些内容不会刷新视图),您将在类上实现INotifyPropertyChanged
接口。这将允许后面的代码向视图发送通知,以便在发生更改时告知它。
以下是实现此目的的C#代码:
public partial class MainPage : UserControl, INotifyPropertyChanged
{
private ObservableCollection<Customer> _MyList =
new ObservableCollection<Customer>();
public ObservableCollection<Customer> MyList
{
get { return _MyList; }
}
public MainPage()
{
InitializeComponent();
this.DataContext = this;
MyList.Add(new Customer{ _nome = "Josimari", _idade = "29"});
MyList.Add(new Customer{_nome = "Wesley", _idade = "26"});
MyList.Add(new Customer{_nome = "Renato",_idade = "31"});
OnPropertyChanged("MyList"); // This only works if you use bindings.
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
MyList.Add(new Customer{_nome = "Maiara",_idade = "18"});
OnPropertyChanged("MyList"); // This only works if you use bindings.
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged( string propertyName )
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}