Search code examples
c#wpfxaml

get name of listbox item on click in wpf xaml


I'm trying a while to get the displayed Value form a listBoxItem onClick.

I've built for testing a button which is doing what I need from the List:

    private void getDomains_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            string selected = allDomains_ListBox.SelectedItem.ToString();
            MessageBox.Show("Item is available " + selected);


        }
        catch (Exception ex)
        {
            MessageBox.Show("Item is not available");

        }
    }

But I need this behavior if I click on a ListItem like:

        private void allDomains_ListBox_MouseLeftButtonDown(object sender, MouseEventArgs e) {
        try
        {
            string selected = allDomains_ListBox.SelectedItem.ToString();
            MessageBox.Show("Item is available " + selected);


        }
        catch (Exception ex)
        {
            MessageBox.Show("Item is not available");

        }
    }

The listItems are generated with:

        public void enum_AllDomains()
    {
        Forest currentForest = Forest.GetCurrentForest();
        DomainCollection domains = currentForest.Domains;
        foreach (Domain objDomain in domains)
        {
            allDomains_ListBox.Items.Add("somedomain.com");
            allDomains_ListBox.Items.Add("google.com");
        }

    }

That's my xaml for the listBox:

<ListBox Width="200" x:Name="allDomains_ListBox" Grid.Column="1" />

Solution

  • You could handle the PreviewMouseLeftButtonDown event for the ListBoxItem container:

    <ListBox Width="200" x:Name="allDomains_ListBox" Grid.Column="1">
        <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem">
                <EventSetter Event="PreviewMouseLeftButtonDown" Handler="ListBoxItem_PreviewMouseLeftButtonDown" />
            </Style>
        </ListBox.ItemContainerStyle>
    </ListBox>
    

    private void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        string clicked = ((ListBoxItem)sender).DataContext.ToString();
        ...
    }