Wpf的comboBox怎么绑定数据?

Wpf的comboBox怎么绑定数据?,第1张

WPF中提供了数据绑定的功能, *** 作起来很方便,集合类的控件几乎都可以用数据源来进行数据的绑定,下面 *** 作一下下拉列表框控件ComboBox控件的数据绑定 *** 作。

要绑定到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好像只能自己写代码绑定了


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/10004673.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-04
下一篇 2023-05-04

发表评论

登录后才能评论

评论列表(0条)

保存