在WPF中动态设置控制模板

时间:2014-04-18 00:59:37

标签: c# wpf templates

 <s:FastLineRenderableSeries.PointMarker>

  <s:SpritePointMarker PointMarkerTemplate="{StaticResource AnyWpfControlTemplateCanGoHere}"/>

根据许多选项中的用户选择,我需要在运行时设置此模板。模板已经在通用字典中定义,就像这样

<ControlTemplate x:Key="RightTriangleAnnotations">
   <Polygon Points="0 0, 20 20,0 20" x:Name="poly" Fill="Green" Stroke="Red"></Polygon>

我的代码是这样的

  var pointMarker = new SpritePointMarker();
  pointMarker.Template = **Here the template should go**
  renderSeries.PointMarker = pointMarker;

任何想法如何在运行时设置模板。

1 个答案:

答案 0 :(得分:1)

基本上,这取决于资源的定义位置。你只需要从字典中获取模板。 例如,如果为应用程序定义了字典:

Application.Current.Resources["RightTriangleAnnotations"] as ControlTemplate

或者,如果在XAML中直接将字典附加到字典,则可以使用任何可视对象,例如 SpritePointMarker :: Resources 。有关详细解决方案,请参阅此问题:How can I access ResourceDictionary in wpf from C# code?

如果您未在任何XAML文件中指定字典,则必须先加载字典,然后将其分配给可视对象,以便能够按键获取所需的资源。请查看此问题以获取详细信息:Access ResourceDictionary items programmatically