I have a user control that applies a style to button, with the style containing a ControlTemplate section. Within the ControlTemplate, there are various UI elements such as an Ellipse and a Path.
我有一个用户控件,它将样式应用于按钮,样式包含ControlTemplate部分。在ControlTemplate中,有各种UI元素,如Ellipse和Path。
If I give those elements -- the Ellipse and Path -- a name with x:Name, can I access them from code behind?
如果我给这些元素 - Ellipse和Path - 一个带x:Name的名称,我可以从后面的代码中访问它们吗?
It appears the style's Ellipse and Path are not visible because I get a compile error (C#).
看起来样式的Ellipse和Path不可见,因为我收到编译错误(C#)。
Am I going about this the wrong way?
我是以错误的方式来做这件事的吗?
1 个解决方案
#1
18
Because a template can be instantiated multiple times, it's not possible to bind a generated member via x:Name
. Instead, you have to find the named element within the template applied to a control.
由于模板可以多次实例化,因此无法通过x:Name绑定生成的成员。相反,您必须在应用于控件的模板中找到命名元素。
Given simplified XAML:
给出简化的XAML:
<ControlTemplate x:Key="MyTemplate">
<Ellipse x:Name="MyEllipse" />
</ControlTemplate>
You would do something like this:
你会做这样的事情:
var template = (ControlTemplate)FindResource("MyTemplate");
template.FindName("MyEllipse", myControl);
Or even more simply:
甚至更简单:
var ellipse = (Ellipse)myControl.Template.FindName("MyEllipse", myControl);
You can read about FrameworkTemplate.FindName
.
您可以阅读FrameworkTemplate.FindName。
Some examples and discussion here, here and here.
这里和这里有一些例子和讨论。
#1
18
Because a template can be instantiated multiple times, it's not possible to bind a generated member via x:Name
. Instead, you have to find the named element within the template applied to a control.
由于模板可以多次实例化,因此无法通过x:Name绑定生成的成员。相反,您必须在应用于控件的模板中找到命名元素。
Given simplified XAML:
给出简化的XAML:
<ControlTemplate x:Key="MyTemplate">
<Ellipse x:Name="MyEllipse" />
</ControlTemplate>
You would do something like this:
你会做这样的事情:
var template = (ControlTemplate)FindResource("MyTemplate");
template.FindName("MyEllipse", myControl);
Or even more simply:
甚至更简单:
var ellipse = (Ellipse)myControl.Template.FindName("MyEllipse", myControl);
You can read about FrameworkTemplate.FindName
.
您可以阅读FrameworkTemplate.FindName。
Some examples and discussion here, here and here.
这里和这里有一些例子和讨论。