Dal*_*lal 4 c# wpf user-controls
假设我已经使用XAML中定义的以下ContentTemplate创建了一个UserControl:
<UserControl.ContentTemplate>
<DataTemplate>
<Ellipse Name="myEllipse" Stroke="White"/>
<ContentPresenter Content="{TemplateBinding Content}"/>
</DataTemplate>
</UserControl.ContentTemplate>
Run Code Online (Sandbox Code Playgroud)
我如何访问我的代码中的"myEllipse"元素,以便,例如,我可以用"myEllipse.Height"找到它的高度?我无法直接通过名称访问它.我尝试使用以下方法创建对它的引用:
Ellipse ellipse = ContentTemplate.FindName("myEllipse",this) as Ellipse;
Run Code Online (Sandbox Code Playgroud)
它在我运行程序时崩溃,说它无法创建我的类的实例.也许我没有正确使用FindName.如果有人可以帮助我,我将不胜感激.
谢谢,
达拉尔
要在DataTemplate上使用FindName,您需要对ContentPresenter的引用.请参阅Josh Smith的文章如何使用ContentControl使用FindName.
您实际想要做的是使用ControlTemplate而不是DataTemplate.这应该更容易使用,并允许您的控件的用户应用他们自己的内容模板或使用隐式模板.如果您这样做:
<UserControl.Template>
<ControlTemplate TargetType="UserControl">
<Grid>
<ContentPresenter/>
<Ellipse Name="myEllipse" Stroke="White"/>
</Grid>
</ControlTemplate>
</UserControl.Template>
Run Code Online (Sandbox Code Playgroud)
然后在代码中(可能在OnApplyTemplate覆盖中),您将能够执行此操作:
var ellipse = Template.FindName("myEllipse", this) as Ellipse;
Run Code Online (Sandbox Code Playgroud)
您还应该使用TemplatePartAttribute来装饰您的类,如下所示:
[TemplatePart(Name="myEllipse", Type = typeof(Ellipse))]
Run Code Online (Sandbox Code Playgroud)
因此,如果有人重新模板化控件,他们就知道提供具有该名称的Ellipse元素.(如果该类仅在内部使用,则不太重要.)
最后,如果你想要做的只是改变Ellipse的颜色,那么你可能只想使用数据绑定.您可以在控件上创建一个EllipseColor依赖项属性,然后进行设置Stroke="{TemplateBinding EllipseColor}".
| 归档时间: |
|
| 查看次数: |
6717 次 |
| 最近记录: |