SilverLight 使用ControlTemplate自定义控件外观、动态修改样式

参考资料 http://msdn.microsoft.com/zh-cn/library/cc189093(v=VS.95).aspx

              http://forums.silverlight.net/forums/p/166296/382041.aspx

 

代码:

(1)使用TemplateBinding 标记扩展绑定ControlTemplate元素的属性。

<Style TargetType="local:ForaEdit">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:ForaEdit">
                                 <Image Cursor="Arrow"  x:Name="PART_Image" Width="{TemplateBinding Width}"   

                                 Height="{TemplateBinding Height}" Source="{TemplateBinding PinSource}"

                                 Stretch="Uniform" RenderTransformOrigin="0.5,0.5" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

(2) 在空间类中定义公共属性PinSource。

在DevPin(自定义控件) 中,定义如下:

public ImageSource PinSource
        {
            get
            {
                return GetValue(PinSourceProperty) as ImageSource;
            }
            set
            {
                SetValue(PinSourceProperty, value);
            }

        }

 public static readonly DependencyProperty PinSourceProperty = DependencyProperty.Register("PinSource", typeof(ImageSource), typeof(DevPin), null);

(3)使用

     BitmapImage bi = new BitmapImage();

     bi.UriSource = new Uri("Resources/cherry3.jpg", UriKind.RelativeOrAbsolute);
     var pin = new DevPin();
           
     pin.Height = 30;
     pin.Width = 30;
     pin.PinSource = bi;

 

说明:

控件类(Control)本身具有可视属性Background、BorderThickness、BorderBrush、FontFamily、FontSize等等,还有Width、Height这些Control本身继承的属性。自定义控件继承自Control,它也将继承这些属性。如果自定义的公共属性与继承的属性相同,就会产生冲突。这时可以修改自定义公共属性的名称,或者不定义公共属性,直接使用,例如Width和Height可以不用定义。

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值