How to access a WPF control located in a ControlTemplate?

隐身守侯 提交于 2019-11-27 13:56:45

You can use the FindName() method of the ControlTemplate class.

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

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:

<Canvas x:Name="myCanvas"/>

You can then access the canvas through the Name as such:

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:

<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".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!