silverlight 控件自定义样式 实现方法

1:在app.xaml中加入需实现的样式,如:

 1   <Application.Resources>
 2      <Style x:Key="NodeStyle" TargetType="VectorModel:Node">
 3              <Setter Property="Template">
 4         <Setter.Value>
 5             <ControlTemplate TargetType="VectorModel:Node"> 
 6                      <Canvas>
 7                     <Grid x:Name="RootElement" MinWidth="5" >
 8                         <Grid.RenderTransform>
 9                             <ScaleTransform x:Name="_ScaleTransform" ScaleX="1" ScaleY="1"/>
10                         </Grid.RenderTransform>
11                         <Ellipse Grid.Row="0" x:Name="pointSty" Height="10" Width="10" Fill="Yellow" Stroke="RoyalBlue" StrokeThickness="2" HorizontalAlignment="Center" VerticalAlignment="Center"/>
12                     </Grid>
13                 </Canvas>
14 
15               </ControlTemplate>
16         </Setter.Value>
17     </Setter> 
18         </Style>
19     </Application.Resources>
View Code

  注意:记得加入控件命名空间引用,如:

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);
            }
原文地址:https://www.cnblogs.com/lj821022/p/3299028.html