0

So the problem I'm having is that I would like to access a ComboBox's ToggleButton, specifically the ToggleButton's "Click" event, but I can't find a good way of accessing the ToggleButton because of the way it's embedded into the ComboBox's Control Template.

I know you can get to it by creating your own Control Template in XAML but I don't want to create a whole new Control Template for the ComboBox for just one tiny change.

Is there any way to access the ToggleButton through C#?

Here's my structure for reference: Visual Tree Structure
(Sorry, not enough points to embed the image)

It's easy to get the ComboBox's Popup/Textbox control using:
comboBox.Template.FindName("PART_Popup", combobox)
comboBox.Template.FindName("PART_EditableTextBox", comboBox)

But the ComboBox's ToggleButton doesn't have a name to call it by.

Taterhead
  • 5,763
  • 4
  • 31
  • 40
Ajrod
  • 1
  • 2
  • This question about finding by name or type is one of the most frequently accessed WPF post on SO: http://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type – Taterhead Mar 05 '16 at 10:40

1 Answers1

1

You can do like this:

var tgs = FindVisualChild<ToggleButton>(comboBox);
if (tgs != null && tgs.Count > 0)
{
    tgs[0].Width = 20;
}

FindVisualChild function:

public static List<T> FindVisualChild<T>(DependencyObject depObj) where T : DependencyObject
{
    if (depObj != null)
    {
        List<T> childItems = null;
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
        {

            if (childItems == null)
                childItems = new List<T>();

            DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
            if (child != null && child is T)
            {
                childItems.Add((T)child);
            }

            var recursiveChildItems = FindVisualChild<T>(child);
            if (recursiveChildItems != null && recursiveChildItems.Count > 0)
                childItems.AddRange(recursiveChildItems);
        }
        return childItems;
    }
    return null;
}
Community
  • 1
  • 1
NoName
  • 7,940
  • 13
  • 56
  • 108