2010-11-23 200 views
0

你可以看我的解决方案here的完整结构,但这里的快速参考:WPF数据绑定:如何将数据绑定到一个集合?

  1. 我在Entities类库做了一个类Account.cs
  2. 我做了一个类库CoreAccountController.cs类从Sql Server表中获取 帐户。
  3. 我在Gui.Wpf.Controllers类库中做了AccountWindowController.cs类的类。 它包含List<Account> Accounts属性,并要求AccountController中的GetAccounts() 方法填充该列表。
  4. 最后,我在Gui.Wpf类库中做了AccountWindow.xaml。此WPF窗口 包含名为AccountsListBoxListBox

我想数据将列表框从AccountWindow绑定到AccountWindowController列表中,但我不知道如何。下面是相关的代码:

AccountWindow.xaml

<Window x:Class="Gui.Wpf.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:controller="clr-namespace:Gui.Wpf.Controllers" 
    Title="Accounts" 
    Width="350" 
    MinWidth="307" 
    MaxWidth="400" 
    Height="500" > 

    <Window.Resources> 
     <controller:AccountWindowController 
      x:Key="AccountsCollection" /> 
    </Window.Resources> 

    <Grid> 
     <ListBox 
      Name="AccountsListBox" 
      Margin="12,38,12,41" 
      ItemsSource="{StaticResource ResourceKey=AccountsCollection}" /> 
    </Grid> 

</Window> 

AccountWindow.xaml.cs

public partial class MainWindow : Window 
{ 
    public MainWindow() 
    { 
     InitializeComponent(); 
     new Gui.Wpf.Controllers.AccountWindowController(); 
    } 
} 

AccountWindowController.cs

public class AccountWindowController 
{ 
    //This event is handled in the AccountController.cs 
    //that sets the Accounts property defined below. 
    public event EventHandler GetAccounts; 

    private List<Account> accounts; 
    public List<Account> Accounts 
    { 
     get 
     { 
      GetAccounts(this, new EventArgs()); 
      return accounts; 
     } 
     set 
     { 
      this.accounts = value; 
     } 
    } 

    //Constructor 
    public AccountWindowController() 
    { 
     new AccountController(this); 
    } 
} 

谢谢你的帮助。

回答

1

ItemsSource需求是一个IEnumerableAccountsCollection资源是一个包含要使用的属性的类。为了做到这一点,你需要绑定到该属性,并使用资源作为绑定的源:(在账户setter和提高PropertyChanged

<ListBox Name="AccountsListBox" 
     Margin="12,38,12,41" 
     ItemsSource="{Binding Accounts, Source={StaticResource ResourceKey=AccountsCollection}}" /> 

你也应该在AccountWindowController 实施INotifyPropertyChanged因此如果您设置了Accounts属性,则ListBox将重新绑定到新集合。如果Accounts集合在运行时被修改,它应该是ObservableCollection

0

它看起来像你几乎在那里。尝试改变

ItemsSource="{StaticResource ResourceKey=AccountsCollection}" /> 

进入

ItemsSource="{Binding Source={StaticResource ResourceKey=AccountsCollection}, Path=Accounts}" /> 
+0

感谢您的回答马修。更改代码导致编译错误,并显示以下错误消息:Error解析标记扩展时遇到类型为“System.Windows.StaticResourceExtension”的未知属性“路径”。我应该改变别的东西吗? – Boris 2010-11-23 19:04:10

+0

道歉,我错过了一些。请再试一次。 – 2010-11-23 20:34:44