1:在app.xaml中加入需实现的样式,如:
<Application.Resources>
<Style x:Key="NodeStyle" TargetType="VectorModel:Node">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="VectorModel:Node">
<Canvas>
<Grid x:Name="RootElement" MinWidth="5" >
<Grid.RenderTransform>
<ScaleTransform x:Name="_ScaleTransform" ScaleX="1" ScaleY="1"/>
</Grid.RenderTransform>
<Ellipse Grid.Row="0" x:Name="pointSty" Height="10" Width="10" Fill="Yellow" Stroke="RoyalBlue" StrokeThickness="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</Grid>
</Canvas> </ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Application.Resources>
注意:记得加入控件命名空间引用,如:
xmlns:VectorModel="clr-namespace:VectorModel;assembly=VectorModel"
2:在自定义控件构造函数中获取样式,如:
this.Style = Application.Current.Resources["NodeStyle"] as Style;
3:可以在类中再变换样式模板中控件的属性,比如在类中修改自定义样式Ellipse的填充颜色为red,如:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
//从样式模板中获取Ellipse控件
this.pointSty = GetTemplateChild("pointSty") as Ellipse;
this.pointSty.Fill = new SolidColorBrush(Colors.Red);
}