How to Get element inside the content control

后端 未结 2 423
面向向阳花
面向向阳花 2021-01-13 17:01

I need to find the element inside the content control :



        
2条回答
  •  一向
    一向 (楼主)
    2021-01-13 17:29

    This method will help you:

    public T FindElementByName(FrameworkElement element, string sChildName) where T : FrameworkElement
        {
                T childElement = null;
                var nChildCount = VisualTreeHelper.GetChildrenCount(element);
                for (int i = 0; i < nChildCount; i++)
                {
                    FrameworkElement child = VisualTreeHelper.GetChild(element, i) as FrameworkElement;
    
                    if (child == null)
                        continue;
    
                    if (child is T && child.Name.Equals(sChildName))
                    {
                        childElement = (T)child;
                        break;
                    }
    
                    childElement = FindElementByName(child, sChildName);
    
                    if (childElement != null)
                        break;
                } 
                return childElement;
        }
    

    And, how I use it, just add button, and on button Click:

     private void Button_OnClick(object sender, RoutedEventArgs e)
        {
            var element = FindElementByName(ccBloodGroup, "cbBloodGroup");
        }
    

提交回复
热议问题