【发布时间】:2010-10-23 15:23:53
【问题描述】:
通常,WPF 控件是在 .xaml 文件中声明的,而不是在后面的代码(.xaml.cs 文件)中声明的。但是,有时我需要在后面的代码中使用其中一些控件来操作它们。如果它“驻留在”xaml 文件中,我如何获取此类控件的句柄?
【问题讨论】:
标签: wpf controls controltemplate
通常,WPF 控件是在 .xaml 文件中声明的,而不是在后面的代码(.xaml.cs 文件)中声明的。但是,有时我需要在后面的代码中使用其中一些控件来操作它们。如果它“驻留在”xaml 文件中,我如何获取此类控件的句柄?
【问题讨论】:
标签: wpf controls controltemplate
您可以使用 ControlTemplate 类的 FindName() 方法。
// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);
【讨论】:
(Grid)myButton1.FindName("grid");(在按钮处理程序中很有用)。
我不确定你在问什么,所以我会尝试回答我解释为你的问题的两个实例。
1) 如果你想声明一个显式控件,然后直接编辑它,你所要做的就是像这样设置 name 属性:
<Canvas x:Name="myCanvas"/>
然后您可以通过名称访问画布,如下所示:
myCanvas.Background = Brushes.Blue;
2) 如果您要声明一个通用控件,然后多次使用它,您可以这样做:
<Window>
<Window.Resources>
<Ellipse x:Key="myEllipse" Height="10" Width="10">
</Window.Resources>
</Window>
然后您可以在代码中使用以下语法访问该预定义控件:
Ellipse tempEllipse = (Ellipse)FindResource("MyEllipse");
如果您想将资源用作多个控件的模板,请添加 x:Shared="false"。
【讨论】: