Reference to a TextBox inside a DataTemplate

前端 未结 3 2083
不知归路
不知归路 2021-01-23 10:27

How do I get a reference to a TextBox that\'s only defined inside a DataTemplate (assuming that I\'ve just applied this DataTemplate to some cell in a grid).

So far I\'m

3条回答
  •  青春惊慌失措
    2021-01-23 11:05

    For getting the reference of a control inside a Data Template, handling the event and then using the sender is one of the available option. There is one more option that you can try:

    in .xaml:

        
            
                
                
                    
                        
                            
                        
                    
                
            
        
        

    in .xaml.cs

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            InitializeMouseHandlersForVisual(datagrid);
        }
    
        public void InitializeMouseHandlersForVisual(Visual visual)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
            {
                Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i);
                if (childVisual is TextBox)
                    MessageBox.Show("textbox Found");
                // Recursively enumerate children of the child visual object.
    
                InitializeMouseHandlersForVisual(childVisual);
            }
        }
    

    Hope this helps!!

    Edit:

    if you want to use x:Name then also you need to at least get the ContentPresenter and for getting ContentPresenter you need to go through the element tree. The updates you need to make are:

    in .xaml:

        
            
         
    

    in .xaml.cs

        public void InitializeMouseHandlersForVisual(Visual visual)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(visual); i++)
            {
                Visual childVisual = (Visual) VisualTreeHelper.GetChild(visual, i);
                ContentPresenter myContentPresenter = childVisual as ContentPresenter;
                if (myContentPresenter != null)
                {
                    // Finding textBlock from the DataTemplate that is set on that ContentPresenter
                    DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
                    if (myDataTemplate != null)
                    {
                        TextBox myTextBox = (TextBox)myDataTemplate.FindName("text", myContentPresenter);
                        MessageBox.Show("textbox Found");
                    }
                }
                InitializeMouseHandlersForVisual(childVisual);
            }
        }
    

    Hope this helps!!

提交回复
热议问题