Nate
Nate

Reputation: 30656

WPF ListBox Button Selected Item

I have a listbox with some textblocks and a button -- in the button's codebehind it calls a method passing the currently selected listbox item, this works great. The issue is that when I select an item and then click the button on another item it doesn't update the "SelectedItem" property -- is there a way Xaml or C# that I can force a button click to select the parent ListBoxItem?

Xaml

<DataTemplate>
    <Grid>
        <Button x:Name="myButton" Click="myButton_Click" Height="30" Width="30">
            <Image Source="Resources\Image.png" />
        </Button>
        <TextBlock Text="{Binding DataField}"></TextBlock>
    </Grid>
</DataTemplate>

Upvotes: 8

Views: 15451

Answers (3)

DiMaAgalakov
DiMaAgalakov

Reputation: 141

You can pass ListBoxItem to the command parameters.

XAML:

<ListBox.ItemTemplate>
    <DataTemplate>
        <Button Command="{Binding DataContext.DeleteItemCommand, ElementName=listBox}" CommandParameter="{Binding}"/>
    </DataTemplate>
</ListBox.ItemTemplate>

CODE:

    public ICommand DeleteItemCommand => new RelayCommand(obj => DeleteItem(obj));
 
    private void DeleteItem(object obj)
    {
        if(obj is ItemName item)
            Items.Remove(item);
    }

Upvotes: 1

rooks
rooks

Reputation: 1796

var curItem = ((ListBoxItem)myListBox.ContainerFromElement((Button)sender)).Content;

Upvotes: 25

Kenan E. K.
Kenan E. K.

Reputation: 14111

When a Button is clicked, it sets e.Handled to true, causing the routed event traversal to halt.

You could add a handler to the Button which raises the routed event again, or finds the visual ancestor of type ListBoxItem and sets its IsSelected property to true.

EDIT

An extension method like this:

public static DependencyObject FindVisualAncestor(this DependencyObject wpfObject, Predicate<DependencyObject> condition)
{
    while (wpfObject != null)
    {
        if (condition(wpfObject))
        {
            return wpfObject;
        }

        wpfObject = VisualTreeHelper.GetParent(wpfObject);
    }

    return null;
}

Usage:

myButton.FindVisualAncestor((o) => o.GetType() == typeof(ListBoxItem))

Upvotes: 4

Related Questions