WPF-ListView的数据绑定
下面讲一下关于ListView的数据绑定. 首先先定义一个用户的类.User,成员Username, Password, API. 前台的xml可以将ListView与List
public class User { private string _username; private string _password; private string _api; public string Username { set { this._username = value; } get { return this._username; } } public string Password { set { this._password = value; } get { return this._password; } } public string API { set { this._api = value; } get { return this._api; } } } public class Users : List<User> { }
前台的代码相对简单一些.
<Window: xmlns:system="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:NameSpace" <!--上面两行是一定要加的,NameSpace换成自己的命名空间--> <!--上面local是为了下面windows.resources中使用的.--> ... <!--这里的resource就是根据server端的User来定义的.--> <Window.Resources> <local:Users x:Key="MyUser"> <local:User Username="User1" Password="Password" API="API1" ></local:User> <local:User Username="User2" Password="Password" API="API2" ></local:User> </local:Users> </Window.Resources> <!--这里的父容器要指定DataContext,即User的组合Users,类型为List. 这样容器里面的内容才可以绑定成员--> <Grid DataContext="{StaticResource MyUser}"> <ListBox Name="lstRecords" ItemsSource="{Binding}"> <!--这里是用来自定义ListView模板的.--> <ListBox.ItemTemplate> <DataTemplate> <TextBox Text="{Binding Path=Username}" ></TextBox> <TextBox Text="{Binding Path=Password}" ></TextBox> <TextBox Text="{Binding Path=API}" ></TextBox> </DataTemplate> </ListBox.ItemTemplate> <ListBox Name="lstRecords" ItemsSource="{Binding}"> </Grid>
到此, ListView就可以显示出用户的列表了. 其中DataTemplate中的格式可以随意更改.
P.S.
如果不喜欢使用前端来控制的话,前台XML可以变成后端的代码.
User usr = new User("username","password","api"); Users users = new Users(); Users.Add(usr); lstName.ItemsSource = users;
Recent Comments