WPF如何更改xaml代码里ListBox的数据绑定

我在xaml代码里已经将一个ListBox的ItemSource绑定到了一个Access数据库的表上,像这样<ListBox Name="lb1" Width="160" ItemsSource="{Binding Path=myClientTable}" DisplayMemberPath="Client_Name"/>
现在我想在后台的C#代码里修改绑定,可以做到吗?怎么弄?谢谢

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>
温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2016-09-26

设计器给ListBox一个标识x:Name="listBox1",然后在代码中写listBox1.ItemSource=数据源就行了~


数据源需要是DataTable,IList集合等。


OleDbAdapter adapter=new OleDbAdapter(cmdText,connStr);
DataTable table=new DataTable();
adapter.Fill(table);
listBox1.ItemSource=table;

本回答被提问者和网友采纳
第2个回答  2013-12-24
想修改成什么?追问

本来是绑定myClientTable这张表,现在想在后台修改为别的表,比如myStaffTable

追答

直接修改ItemsSource=Table.DefaultView和DisplayMemberPath不就行了

相似回答