要绑定到ComboBox控件的自定义类:
public class LocationRoad
{
public int ID { setget}
public string Code { setget}
public string Info { setget}
}
建立数据源,就将此数据集合当作数据源绑定到ComboBox:
///
/// 当ComboBox选中项更改时发生
///
private LocationRoad _selectLocation
public LocationRoad SelectLocation
{
get
{
return this._selectLocation
}
set
{
this._selectLocation = value
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("SelectLocation"))
}
}
private ObservableCollection _locationRoad = null
public ObservableCollection LocationSource
{
get
{
if (this._locationRoad == null)
{
this._locationRoad = new ObservableCollection() {
new LocationRoad() { ID = 1, Code = "NGQ", Info = "南岗区" },
new LocationRoad() { ID = 2, Code = "DLQ", Info = "道里区" },
new LocationRoad() { ID = 3, Code = "DWQ", Info = "道外区" },
new LocationRoad() { ID = 4, Code = "PFQ", Info = "平房区" },
new LocationRoad() { ID = 5, Code = "XFQ", Info = "香坊区" },
}
}
return this._locationRoad
}
set
{
this._locationRoad = value
if (this.PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("LocationSource"))
}
}
1:新建一个WPF工程,并在XAML文件中添加一个ListBox控件,如下:<Window x:Class="ListBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
title="Window1" Height="800" Width="300">窗口1 高度 宽度
<Grid>
<ListBox />
</Grid>
</Window>
2:在cs文件中添加一个类,并在其构造函数中获取系统当正在运行的进程的名称,代码如下:
using System.Collections.Generic
using System.Windows
namespace ListBinding
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent()
}
}
public class Processes : List<string>
{
public Processes()
{
//在构造函数中取得系统中进程的名称并将其添加到类中
System.Diagnostics.Process[] pList = System.Diagnostics.Process.GetProcesses()
foreach (System.Diagnostics.Process p in pList)
{
this.Add(p.ProcessName)
}
}
}
}
3:下面要进行控件与数据的绑定,修改后的XAML文件内容如下:
<Window x:Class="ListBinding.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:ListBinding"
title="Window1" Height="800" Width="300">
<Window.Resources>
<src:Processes x:Key="p"/>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{StaticResource p}"/>
</Grid>
</Window>
dataGrid1_SelectionChanged(object sender, SelectionChangedEventArgs e)是如果你选择项有改变的时候触发的事件dataGrid好像是可以直接绑定到数据库,但是listview好像只能自己写代码绑定了
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)