参考资料 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可以不用定义。