WPF数据绑定:如何绑定集合的数据?

时间:2010-11-23 18:01:23

标签: wpf data-binding binding

您可以阅读我的解决方案here的完整结构,但这里是快速参考:

  1. 我在Account.cs类库中创建了一个类Entities
  2. 我创建了一个类库Core,其中包含一个类AccountController.cs 来自Sql Server表的帐户。
  3. 我在AccountWindowController.cs类库中创建了一个类Gui.Wpf.Controllers。 它包含List<Account> Accounts属性并调用GetAccounts() AccountController中填充该列表的方法。
  4. 最后,我在AccountWindow.xaml类库中创建了Gui.Wpf。这个WPF窗口 包含名为ListBox的{​​{1}}。
  5. 我想将AccountsListBox的列表框数据绑定到AccountWindow中的列表,但我不知道如何。这是相关的代码:

    AccountWindow.xaml

    AccountWindowController

    AccountWindow.xaml.cs

    <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>
    

    AccountWindowController.cs

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

    感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

ItemsSource必须是IEnumerableAccountsCollection资源是包含要使用的属性的类。为此,您需要绑定到该属性,并使用该资源作为绑定源:

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

您还应该在AccountWindowController上实现INotifyPropertyChanged  (并在Accounts setter中引发PropertyChanged,这样如果您设置Accounts属性,ListBox将重新绑定到新集合。如果在运行时修改了Accounts集合,它应该是ObservableCollection

答案 1 :(得分:0)

看起来你几乎就在那里。尝试更改

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

ItemsSource="{Binding Source={StaticResource ResourceKey=AccountsCollection}, Path=Accounts}" />
相关问题