[WPF]listview的使用方法
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-26 21:47:15
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
添加多列信息头
<ListView Name="hostlist"> <ListView.View> <GridView FrameworkElement.FlowDirection="RightToLeft"> <GridViewColumn Header="主机ip地址" > <!-- 可以定义Cell的模板 --> <GridViewColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding host}" TextDecorations="Underline" Foreground="Blue" Cursor="Hand" /> </DataTemplate> </GridViewColumn.CellTemplate> </GridViewColumn> <GridViewColumn Header="端口" DisplayMemberBinding="{Binding port}" /> <GridViewColumn Header="登陆账号" DisplayMemberBinding="{Binding account}" /> <GridViewColumn Header="状态" DisplayMemberBinding="{Binding status}" /> </GridView> </ListView.View> </ListView>
如图
添加列表数据
实现数据绑定来更新界面
首先给每一列数据定义一个类并且实现 INotifyPropertyChanged 接口
HostList.cs
class HostList : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string _host; public string host { get { return _host; } set { _host = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("host")); } } } private string _port; public string port { get { return _port; } set { _port = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("port")); } } } private string _account; public string account { get { return _account; } set { _account = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("account")); } } } private string _status; public string status { get { return _status; } set { _status = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("status")); } } } }
给listview设置数据源并显示
在界面初始化函数里加入下面代码
//定义一个列表集合,设置给listview的数据源 List<HostList> s = new BindingList<HostList>(); for (int i = 0; i < 10; i++) { s.Add(new HostList { host = "1.1.1.1", port = "80", account = "7355879", status = "正常" }); } hostlist.ItemsSource = s;
修改数据界面同步更新
//按钮单击事件里写 HostList li = hostlist.Items[0] as HostList; li.port = "8080";
选中列表项后弹出对应信息
private void hostlist_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { //取当前选中的一行,此行数据你原来绑定的是什么类型还是什么类型 HostList hl = hostlist.SelectedItem as HostList; MessageBox.Show(hl.host); }