Martin Gabriel
Martin Gabriel

Reputation: 59

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?

Upvotes: 0

Views: 1084

Answers (2)

Bolu
Bolu

Reputation: 8786

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

Upvotes: 1

Nitin Purohit
Nitin Purohit

Reputation: 18580

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?

Upvotes: 0

Related Questions