如何访问位于ControlTemplate中的WPF控件?

如何访问位于ControlTemplate中的WPF控件?,wpf,controls,controltemplate,Wpf,Controls,Controltemplate,通常,WPF控件在.xaml文件中声明,而不是在代码隐藏(.xaml.cs文件)中声明。然而,有时我需要在代码隐藏中使用一些控件来操作它们。如果控件“驻留”在xaml文件中,如何获取该控件的句柄?可以使用ControlTemplate类的FindName()方法 // Finding the grid that is generated by the ControlTemplate of the Button Grid gridInTemplate = (Grid)myButton1.Templ

通常,WPF控件在.xaml文件中声明,而不是在代码隐藏(.xaml.cs文件)中声明。然而,有时我需要在代码隐藏中使用一些控件来操作它们。如果控件“驻留”在xaml文件中,如何获取该控件的句柄?

可以使用ControlTemplate类的FindName()方法

// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);

我不确定你在问什么,所以我会尝试回答我解释为你的问题的两个例子

(一) 如果要声明显式控件,然后直接对其进行编辑,只需设置name属性,如下所示:

<Canvas x:Name="myCanvas"/>
(二) 如果您希望声明一个泛型控件,然后多次使用它,您可以这样做:

<Window>
   <Window.Resources>
      <Ellipse x:Key="myEllipse" Height="10" Width="10">
   </Window.Resources>
</Window>

如果要将资源用作多个控件的模板,请添加x:Shared=“false”。

FindName()始终返回null。FindResource()适用于我的应用程序。谢谢。这为我返回了一个空异常,然后我在这里尝试一些不同的答案时意识到了一些问题,所以:如果你正在查找的模板应用于myButton1,请使用CSharper的答案。但如果myButton1只是所述模板的一个成员,则使用
(Grid)myButton1.FindName(“Grid”)相反(在按钮处理程序中很有用)。
<Window>
   <Window.Resources>
      <Ellipse x:Key="myEllipse" Height="10" Width="10">
   </Window.Resources>
</Window>
Ellipse tempEllipse = (Ellipse)FindResource("MyEllipse");