Xaml 从视图到达ContentControl中的控件';s代码隐藏

Xaml 从视图到达ContentControl中的控件';s代码隐藏,xaml,uwp,Xaml,Uwp,我的视图的XAML只包含一个自定义控件 再进一步,在资源字典中,我有一个自定义控件的样式,在这个样式中,我有一个文本框。我的目标是在视图的DataContext发生变化时,从视图的代码隐藏中访问这个文本框,并设置它的焦点 我尝试使用x:Name为视图的XAML上的自定义控件命名,同时也为控件样式中的文本框命名(因此基本上是尝试从代码后面访问它,如:this.MyCustomControl.SearchTextBox)。这不起作用 解决这个问题的最佳做法是什么?这就是我要做的 为文本框在自定义控件

我的视图的XAML只包含一个自定义控件

再进一步,在资源字典中,我有一个自定义控件的样式,在这个样式中,我有一个文本框。我的目标是在视图的DataContext发生变化时,从视图的代码隐藏中访问这个文本框,并设置它的焦点

我尝试使用x:Name为视图的XAML上的自定义控件命名,同时也为控件样式中的文本框命名(因此基本上是尝试从代码后面访问它,如:this.MyCustomControl.SearchTextBox)。这不起作用


解决这个问题的最佳做法是什么?

这就是我要做的

  • 文本框
    在自定义控件顶部创建一个
    TemplatePart
    属性

    // You might want to add property error handling here
    // so if the TextBox is not found, throw an exception.
    // Doing so forces other people will have to implement
    // the SAME PART in their own stylings.
    _textBox = (TextBox)GetTemplateChild("YourTextBoxName");
    
    [模板部分(Name=“YourTextBoxName”,Type=typeof(TextBox))]

  • 然后在应用程序模板的
    覆盖方法中,获取
    文本框的引用

    // You might want to add property error handling here
    // so if the TextBox is not found, throw an exception.
    // Doing so forces other people will have to implement
    // the SAME PART in their own stylings.
    _textBox = (TextBox)GetTemplateChild("YourTextBoxName");
    
  • 然后,您只需要创建一个公共方法
    SetFocus
    ,代码隐藏类可以访问该方法

    public void SetFocus()=>\u textBox.Focus(FocusState.programmabled)


  • 尝试可视化树助手

                VisualTreeHelper.GetChild(object, index)
    

    此文本框是否位于自定义控件的ControlTemplate内?是的,它位于ControlTemplate内