如何访问位于 ControlTemplate 中的 WPF 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/820201/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access a WPF control located in a ControlTemplate?
提问by CSharper
Usually, the WPF controls are declared in the .xaml files and not in the code behind (.xaml.cs files). However, sometimes I need to use some of those controls in code behind in order to manipulate them. How can I get the handle of such a control if it "resides" in the xaml file?
通常,WPF 控件是在 .xaml 文件中声明的,而不是在后面的代码(.xaml.cs 文件)中声明的。但是,有时我需要在后面的代码中使用其中一些控件来操作它们。如果此类控件“驻留在”在 xaml 文件中,我如何获得它的句柄?
回答by CSharper
You can use the FindName() method of the ControlTemplate class.
您可以使用 ControlTemplate 类的 FindName() 方法。
// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);
回答by Drew McGhie
I'm unsure about what you're asking, so I'll try and answer both instances that I'm interpreting as your question.
我不确定你在问什么,所以我会尝试回答我解释为你的问题的两个实例。
1) If you want to declare an explicit control, and then edit it directly, all you have to do is set the name property like such:
1) 如果你想声明一个显式控件,然后直接编辑它,你所要做的就是像这样设置 name 属性:
<Canvas x:Name="myCanvas"/>
You can then access the canvas through the Name as such:
然后,您可以通过 Name 访问画布,如下所示:
myCanvas.Background = Brushes.Blue;
2) If you're looking to declare a generic control, and then use it multiple times, you can do it like this:
2)如果你想声明一个通用控件,然后多次使用它,你可以这样做:
<Window>
<Window.Resources>
<Ellipse x:Key="myEllipse" Height="10" Width="10">
</Window.Resources>
</Window>
You can then access that predefined control using this syntax in code:
然后,您可以在代码中使用以下语法访问该预定义控件:
Ellipse tempEllipse = (Ellipse)FindResource("MyEllipse");
If you want to use the Resourse as a template for multiple controls, add x:Shared="false".
如果要使用资源作为多个控件的模板,请添加 x:Shared="false"。