2011-07-18 93 views
1

更新:到目前为止,我已根据您的帮助更新了代码,但仍然没有运气。当应用程序加载ListBox时没有项目。我给你的垃圾值,让客户在窗户的构造器,然后我也尝试设置ListBox的DataContext的如下:将收藏绑定到WPF列表框

CustomerList.DataContext = Customers; 

--- 原始的问题(与更新的代码)---

我在WPF项目中遇到数据绑定问题。

我有一个类,客户,如下:

public class Customer 
{ 
    public String Name { get; set; }  
    public String Email { get; set; } 
} 

在我的XAML代码后面我有客户的集合如下:

public List<Customer> Customers { get; set; } 

我想每一个客户绑定到带有ListItemTemplate的ListBox,在TextBox中显示客户的信息(名称/电子邮件)以及锁定/解除文本框(将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> 
+0

什么不工作? – ChrisF

+0

“顾客”是一个领域还是一个财产?对于绑定工作,它必须是一个财产。 – svick

+0

你已经给了你的'CollectionViewSource'和你的'DataTemplate'。将密钥更改为其中一个独特的密钥。 –

回答

0

您需要更改

ItemsSource="{Binding Source=Customers}" 

ItemsSource="{Binding Source={StaticResource Customers}}" DataContext="{StaticResource Customers}" 
+2

Or ItemsSource =“{Binding Source = {StaticResource Customers}}” –

+0

实际上*只有* Jerry的版本应该可以工作,因为你不能直接使用'CollectionViewSource'作为'ItemsSource'。此外,DataContext需要设置在某个地方。 –

+0

@ H.B。我应该如何设置DataContext?我目前正按照我窗口构造函数中更新后的问题所述进行设置。那是对的吗?谢谢! – evan

0

尝试设置你的CustomerList的ItemsSource如下:ItemsSource="{Binding}"。您已将ListBox的DataContext设置为客户列表,您需要将ItemsSource设置为相同的集合,因此需要将直接绑定。

如果您喜欢使用CollectionViewSource,您可以做的另一件事是将窗口的DataContext设置为相同的类DataContext=this,因为没有这些,资源定义将无法找到“客户“集合,您在后面的代码中定义。但是,如果您这样做,则不需要CustomerList.DataContext = Customers;,因为您直接将ItemsSource分配给静态资源,而不是相对于DataContext。

还有一件事。我认为你应该在不同名字背后的代码中提供CollectionViewSource和相应的集合。这不会导致运行时的问题,但它使得它很难维护代码;)

希望这有助于:)

1

类似的代码更新的一个变化

<TextBox Content="{Binding Name}" /> 
后,对我的作品

<TextBox Text="{Binding Name}" /> 

由于TextBox没有Content财产(如Label),前者拒绝编译VS.

那么,它被设置为Text中定义:

[ContentPropertyAttribute("Text")] 
public class TextBox : TextBoxBase, IAddChild 

但我认为这只是括号(<TextBox>Like so</TextBox>)之间使用?

这可能是问题的根源吗?

+0

+1我看到了同样的问题 – toxicate20