Chris
Chris

Reputation: 235

Custom ListBox selection in WPF

I have a Custom ListBox with multiple columns per one Item

<ListBox Name="UserListBox" Loaded="GetUsers_OnLoad" SelectionChanged="UserSelected">
<ListBox.ItemTemplate>
    <DataTemplate>
        <DockPanel Name="UserDockPanel" Margin="4">
            <TextBlock Name="UsernameTextBlock" Text="{Binding Path=Username}"/>
            <CheckBox Name="OneCheckBox" IsHitTestVisible="False" IsChecked="{Binding One}" />
            <CheckBox Name="TwoCheckBox" IsHitTestVisible="False" IsChecked="{Binding Two}" />
            <CheckBox Name="ThreeCheckBox" IsHitTestVisible="False" IsChecked="{Binding Three}" />
        </DockPanel>
    </DataTemplate>
</ListBox.ItemTemplate>

What I am trying to do is when the user selects an item that I can parse the individual values for that item (UsernameTextBlock, OneCheckbox, TwoCheckBox, ThreeCheckBox).

I have tried selected which throws an error and selection changed seems to work but I do not know how to retrieve the individual values for the item selected.

Any insight would be appreciated.

UPDATE:

Here is the code behind

private void UserSelected(object sender, RoutedEventArgs e)
{
    var userListBox = FindName("UserListBox") as ListBox;

    var selectedItem = userListBox.SelectedItem as ListBoxItem;

    MessageBox.Show(selectedItem.Username);
}

I am currently just showing a message popup to show what I am accessing

UPDATE 2:

private void GetUsers_OnLoad(object sender, RoutedEventArgs e)
{
    _outreachAuths = _outreachTableAdapter.GetOutreachAuths();

    var users = new List<UserItem>();

    foreach (DataRow row in _outreachAuths.Rows)
    {
        users.Add(new UserItem() { Username = row.ItemArray[0].ToString(), One = false, Two = true, Three = ((row.ItemArray[2].ToString() == "1"))});
    }

    var userList = sender as ListBox;
    if (userList != null) userList.ItemsSource = users;
}

Upvotes: 1

Views: 528

Answers (2)

goobering
goobering

Reputation: 1553

In your UserSelected handler you're casting the selected item to type ListBoxItem:

var selectedItem = userListBox.SelectedItem as ListBoxItem;

In order to access the properties you're looking for you'll need to cast it to its original type which is, I believe, UserItem.

var selectedItem = userListBox.SelectedItem as UserItem;

Upvotes: 1

Bradley Uffner
Bradley Uffner

Reputation: 17001

Bind the listbox's SelectedItem property to a property in your view model. You will then have access to the item when it's value changes in the VM.

<ListBox Name="UserListBox" Loaded="GetUsers_OnLoad" SelectionChanged="UserSelected" SelectedItem={Binding Path=PropertyOnViewModel}>

Upvotes: 0

Related Questions