How do I get the ToggleButton from ComboBox Control

断了今生、忘了曾经 提交于 2019-12-13 16:36:52

问题


I was checking control template of ComboBox(http://msdn.microsoft.com/en-us/library/ms752094(v=vs.110).aspx), where they have used Toggle Button to toggle the Popup. Is there a way I could get the toggle button from code behind?

I had tried this, but to no avail :-(

var uiElement = (ComboBox)sender;
var toggleButton = uiElement.FindResource(typeof(ToggleButton)) as ToggleButton;

回答1:


If you now the name of the ToggleButton then you can use following code:

var uiElement = (ComboBox)sender;
var toggleButton = uiElement.Template.FindName("<Your ToggleButton Name Here>",uiElement) as ToggleButton;

if(toggleButton!=null)
{
     // Your code goes here.
}

If you don't know the name of the ToggleButton then in that case the only option is to travers through visual tree and find an element of type toggle button. Sample code below:

    internal static List<T> FindVisualChild<T>(this 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;
    }

Above method is an extension to DependencyObject and will return all the elements of the specified type from the visual tree. If you want only first element of specified type then you can make slight changes in the method and can break the loop when you get the first element of the specified type and return it.




回答2:


This thing got me answer.

var uiElement = (ComboBox)sender;
var toggleButton = uiElement.FindName("ToggleButton") as ToggleButton;


来源:https://stackoverflow.com/questions/21282978/how-do-i-get-the-togglebutton-from-combobox-control

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!