简体   繁体   中英

WPF Binding IEnumerable to ListBox with a DataTemplate

I am trying to bind an IEnumerable class UserList to a ListBox in XAML, but I'm not able to resolve the name of the object. My xaml code is as follows:

            <ListBox DockPanel.Dock="Left" x:Name="UserListBox" Width="400"
                     ItemsSource="{Binding Source={StaticResource userList}}"
                     ItemTemplate="{StaticResource UserListTemplate}">

            </ListBox>

I have userList instantiated in MainWindow.xaml.cs as well, but I guess I'm not doing something right. Intention is to have ListBox read from UserList and create a list of Users from that IEnumerable. How do I fix this?

public MainWindow()
    {
        InitializeComponent();
        DataConnection.CreateAndOpenDB();
        src.UserList userList = new src.UserList();


    }

A local variable can not be resolved by the StaticResource extension.

Create a UserList property like shown below, and set the Window's DataContext to this . If you want to be able to add or remove elements after setting the DataContext, the class UserList should implement the INotifyCollectionChanged interface. It may do so by deriving from ObservableCollection .

public src.UserList UserList { get; } = new src.UserList();

public MainWindow()
{
    InitializeComponent();
    DataConnection.CreateAndOpenDB();
    // add elements to UserList here

    DataContext = this;
}

Then write the Binding in XAML like this:

ItemsSource="{Binding UserList}"

See Data Binding Overview for an introduction.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM