不多说,先直接上代码
- 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:Li |

本文详细介绍了WPF中ListView的数据绑定,包括绑定到列表数据、当前项、显示成员、数据模板、列表变化、排序、过滤和分组等。通过示例代码展示了如何实现列表的实时更新、排序和分组,以及使用数据模板自定义UI展示。
最低0.47元/天 解锁文章
509

被折叠的 条评论
为什么被折叠?



