通常,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);

其他提示

我不确定你在问什么,所以我会尝试回答我正在解释的两个实例。

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");

如果您想将Resourse用作多个控件的模板,请添加x:Shared =&quot; false&quot;。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top