You may read the complete structure of my solution here, but here’s the quick reference:
- I made a class
Account.csin theEntitiesclass library. - I made a class library
Corewith a classAccountController.cswhich gets the
accounts from the Sql Server tables. - I made a class
AccountWindowController.csin theGui.Wpf.Controllersclass library.
It contains theList<Account> Accountsproperty and calls for theGetAccounts()
method in theAccountControllerto fill that list. - Finally, I made a
AccountWindow.xamlin theGui.Wpfclass library. This WPF window
contains aListBoxnamedAccountsListBox.
I want to data bind the list box from AccountWindow to the list in the AccountWindowController, but I don’t know how. Here’s the relevant code:
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);
}
}
Thank you for all the help.
The
ItemsSourceneeds to be anIEnumerable. TheAccountsCollectionresource is a class that contains the property you want to use. In order to do this, you need to bind to that property, and use the resource as the source of the binding:You should also implement
INotifyPropertyChangedon the AccountWindowController(and raise
PropertyChangedin the Accounts setter) so that if you set the Accounts property, theListBoxwill rebind to the new collection. And if the Accounts collection is modified at runtime, it should be anObservableCollection.