【发布时间】:2011-07-18 20:45:46
【问题描述】:
更新:到目前为止,我已经根据您的帮助更新了代码,但仍然没有成功。当应用程序加载时,ListBox 没有任何项目。我在 windows 的构造函数中为客户分配垃圾值,然后我还尝试将 ListBox 的 DataContext 设置如下:
CustomerList.DataContext = Customers;
--- 原始问题(带有更新的代码)---
我在 WPF 项目中遇到数据绑定问题。
我有一个类 Customer,如下所示:
public class Customer
{
public String Name { get; set; }
public String Email { get; set; }
}
在我背后的 XAML 代码中,我有一组客户如下:
public List<Customer> Customers { get; set; }
我正在尝试使用 ListItemTemplate 将每个客户绑定到一个 ListBox,该 ListItemTemplate 在 TextBoxes 中显示客户的信息(姓名/电子邮件)以及一个锁定/解锁 TextBoxes 的按钮(将 IsEnabled 属性设置为 true 或 false)。
最好的方法是什么?
到目前为止,我一直在尝试追随他,但没有成功。
在 XAML 中,我目前有以下内容(暂时忽略切换部分,我只是想让集合本身被列出。):
<Window.Resources>
<CollectionViewSource x:Key="Customers" Source="{Binding Path=Customers, Mode=TwoWay}"/>
<DataTemplate x:Key="Customer">
<StackPanel Orientation="Horizontal">
<TextBox Content="{Binding Name}" />
<TextBox Content="{Binding Email}" />
</StackPanel>
</DataTemplate>
</Window.Resources>
<StackPanel>
<ListBox ItemsSource="{Binding Source={StaticResource Customers}}"
ItemTemplate="{StaticResource ResourceKey=Customer}"
Name="CustomerList"
Height="300" />
</StackPanel>
【问题讨论】:
-
Customers是字段还是属性?要使绑定起作用,它必须是一个属性。 -
您为您的
CollectionViewSource和您的DataTemplate提供了相同的密钥。将密钥更改为其中一个独特的东西。 -
@ChrisF,当我运行应用程序时,ListBox 中没有显示任何项目,所以我假设数据绑定由于某些原因无法正常工作。
-
@svick,Customers 是 MainWindow.xaml.cs 的一个属性
-
我认为您不需要指定 List 的 DataContext,它不使用它(因为它指定了源),而是将窗口设置为包含
Customers的任何对象,因为在 CollectionViewSource 中您只指定了一个路径,因此 DataContext 将用作基本源。如果您不熟悉这一切,请阅读 MSDN 上的文章,例如 Data Binding Overview。
标签: c# wpf xaml data-binding