Cubi73
Cubi73

Reputation: 1951

Get value of listbox item with item template

I have a window with a property called IpList of type ObervableCollection<string> and I set the window's DataContext property to the window itself so that I can bind properties from XAML elements to properties of the window. One XAML element in my window is a ListBox that has an ItemTemplate:

<ListBox
    ItemsSource="{Binding IpList}"
    x:Name="lbIps">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <DockPanel>
                <Button
                    Click="lbIps_bnClose_Click"
                    Content="X"
                    DockPanel.Dock="Left" />
                <TextBlock
                    Text="{Binding}" />
            </DockPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I want the list box items to remove themselves when their "X" button is clicked. My first attempt was to obtain the selected item index and remove this from the list. But when I only click on the button, no item is selected. My second attempt was to remove the item by value instead of index, but I couldn't figure out how to obtain the value of the list box item containing the clicked button. So my questions are: Is there a possibility to obtain the index/value of the list box item containing the clicked button? If so, how can I do this? Is there another way to remove the parent list box item of a clicked "X" button?

Upvotes: 0

Views: 1574

Answers (2)

The One
The One

Reputation: 4784

If you're not using MVVM:

Put this in the click event

string s=(string)((sender as Button).DataContext);
IpList.Remove(item); 

Upvotes: 0

Fede
Fede

Reputation: 44038

private void lbIps_bnClose_Click(object sender, RoutedEventArgs e)
{
   var vm = this.DataContext as [yourViewModelName];

   var button = sender as Button;

   var item = (string)button.DataContext;

   vm.IpList.Remove(item);
}

Upvotes: 2

Related Questions