您的位置:首页 > 其它

WPF中,ListBox与数据间的绑定

2008-12-20 10:54 501 查看
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">
    <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>

在上面的内容中,添加了一个命名空间src,其所代表的空间就是cs文件中定义的ListBinding;然后又以资源的方式向ListBox中添加了所有进程的名称。
由此就完成了ListBox与进程名称之间的绑定。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: