不多说,先直接上代码
- public class Student : INotifyPropertyChanged
- {
- public event PropertyChangedEventHandler PropertyChanged; // 这个接口仅包含一个事件而已
- private int id;
- public int Id
- {
- get { return id; }
- set
- {
- id = value;
- if ( this .PropertyChanged != null )
- {
- this .PropertyChanged.Invoke( this , new PropertyChangedEventArgs( "Id" )); // 通知Binding是“Id”这个属性的值改变了
- }
- }
- }
- }
public class Students : ObservableCollection<Student>
{
}
<Window.Resource>
<local:Students x:Key="Students">
<local:Student Id="111" />
<local:Student Id="222" />
</local:Students>
</Window.Resource>
<ListView ItemsSource="{StaticResource Students}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBox Text="{Binding Path=Id}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
再来看看别人文章,里面有如何分类,排序的方法,仔细看哟!
1 Binding to List Data
前面都是绑定到一个对象,下面我们学习绑定到对象列表的方法。
我们还是先组织要绑定的数据,对象所对应的类还是Person,但新增了一个新类People,该类用来组织Person的列表.代码如下:
using System; using System.Collections.Generic; using System.ComponentModel;//INotifyPropertyChanged namespace SimpleDataBinding { class Person : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string PropName) { if (this .PropertyChanged != null ) { PropertyChanged(this , new PropertyChangedEventArgs (PropName)); } } public Person() { _Age = 0; _name = "Null" ; this .CurrentDate = DateTime .Now; } private string _name; public string Name { get { return _name; } set { if (value == _name) { return ; } _name = value ;//注意:不能用this.Name来赋值,如果这样形成循环调用,栈溢出 Notify("Name" ); } } private int _Age; public int Age { get { return _Age; } set { if (value == _Age) return ; _Age = value ; Notify("Age" ); } } public DateTime CurrentDate { get ; set ; } } //People类 class People : List <Person > { } } |
注意在同一命名空间下的代码最后添加了Perople类。
我们在UI里显示的XAML如下:
< Window x : Class ="ListDataBinding.BindListDataTest" xmlns ="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns : x ="http://schemas.microsoft.com/winfx/2006/xaml" xmlns : src ="clr-namespace:ListDataBinding" Title ="BindListDataTest" Height ="113" Width ="300"> < Window.Resources > < src : People x : Key =& |