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

24 wpf controls controltemplate

通常,WPF控件在.xaml文件中声明,而不是在后面的代码中声明(.xaml.cs文件).但是,有时我需要在代码中使用其中的一些控件来操作它们.如果它"驻留"在xaml文件中,我如何获得这种控件的句柄?

CSh*_*per 33

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

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