简体   繁体   中英

How to find item by name from listbox

I have listbox with Buttons. Every button have specific name -> button.Name = "button1".

I want to find specific button in listbox by Name.

I tried something like this:

if (listBox.Items.Contains(new Button().Name = "button2"))
{
    MessageBox.Show("TEST");
}

But it doesnt work.

How to find it?

You need to check: 1. If the item is a Button 2. If its name is the same (use == not = as in your code)

foreach(var i in listBox.Items)
{    
    if (i is Button && (i as Button).Name=="button2")
    {
        MessageBox.Show("TEST");
    }    
}

If you have your ItemsControl item with you then you can iterate its Visualtree to reach to your button using VisualTreeHelper

Recursive find child is explained in this post How can I find WPF controls by name or type?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM