簡體   English   中英

在 wpf xaml 中單擊獲取列表框項目的名稱

[英]get name of listbox item on click in wpf xaml

我正在嘗試從 listBoxItem onClick 中獲取顯示的值。

我已經為測試一個按鈕而構建,該按鈕正在執行我從列表中需要的操作:

    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");

        }
    }

但是如果我點擊一個 ListItem,我需要這種行為:

        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");

        }
    }

listItems 是通過以下方式生成的:

        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");
        }

    }

這是我的列表框 xaml:

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

您可以處理ListBoxItem容器的PreviewMouseLeftButtonDown事件:

<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();
    ...
}

您可以將發件人 object 轉換為 ListBoxItem,並可以訪問名稱等所有屬性。

private void getDomains_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            ListBoxItem lstBoxItem = (ListBoxItem)sender;
            MessageBox.Show("Item is available " + lstBoxItem.Name);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Item is not available");

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM