Martin Gabriel
Martin Gabriel

Reputation: 59

How to find source object of added button

I have dynamically added button to a listbox. I'm working with that button and I have to know where this button is located.

I have this method:

private void addNewButton_Click(object sender, RoutedEventArgs e)
    {
        if(sender.GetType().IsSubclassOf(typeof(Control)))
        {
            Control formControl = (Control)sender;
            switch (formControl.Name)
            {
                case "addSound20":
                case "addSound21":
                case "addSound23":
                case "addSound24":
                case "addSound25":
                case "addSound26":
                    MessageBox.Show("test: " + formControl.Name);
                    // there I need to know, where is this button located
                    break;
                default:
                    MessageBox.Show("exception: default");
                    break;
            }
        }
    }

How can I find the source object of my button?

EDIT: I have some ListBoxes in mainWindow - and I need to know, which ListBox contains that Button I'm working with. Every object has specific name - for example "button20", "listBox22", etc.

Upvotes: 1

Views: 118

Answers (2)

Sayse
Sayse

Reputation: 43300

Judging from your last comment, you can cast and use Parent

((ListBox)formControl.Parent).Items.Remove(formControl);

Note: Parent can return null you may wish to check it

formControl.Parent != null && formControl.Parent is ListBox

Upvotes: 2

Nitin Purohit
Nitin Purohit

Reputation: 18580

You can use VisualTreeHelper to find the parent of any control... below method can help you..

        public static T FindAncestor(DependencyObject dependencyObject)
            where T : DependencyObject
        {
            var parent = VisualTreeHelper.GetParent(dependencyObject);

            if (parent == null) return null;

            var parentT = parent as T;
            return parentT ?? FindAncestor(parent);
        }

You can call this method like LisBox lisbox = FindAncestor(formControl);

Upvotes: 0

Related Questions