将模板属性值绑定到模板控件属性
问题描述:
标题有点模糊,问题是:将模板属性值绑定到模板控件属性
我正在实现一个Silverlight 4按钮,通过交换模板和我自己的。是否可以将边框圆角半径绑定到按钮高度?
例如,用户可以设置高度设计师为30,则该模板内边界的角部半径应15.当高度为50,则角半径应为25,等
如果可能的,我需要一个纯粹的XAML解决方案。
谢谢
答
这是没有纯粹的Xaml解决方案。最终,您至少需要执行y/2表达式,而这不是现有基于Xaml的组件提供的内容。
在Vs2010中打开项目。添加一个新项目...“Silverlight模板控制”称它为“RoundEndedButton”。
与更换来源: -
public class RoundEndedButton : Button
{
public RoundEndedButton()
{
this.DefaultStyleKey = typeof(RoundEndedButton);
SizeChanged += new SizeChangedEventHandler(RoundEndedButton_SizeChanged);
}
public static readonly DependencyProperty CornerRadiusProperty =
DependencyProperty.Register(
"CornerRadius",
typeof(CornerRadius),
typeof(RoundEndedButton),
new PropertyMetadata(new CornerRadius()));
void RoundEndedButton_SizeChanged(object sender, SizeChangedEventArgs e)
{
SetValue(CornerRadiusProperty, new CornerRadius(e.NewSize.Height/2));
}
}
在主题/ Generic.xaml修改其默认模板。这里是我非常简单的例子: -
<Style TargetType="local:RoundEndedButton">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="local:RoundEndedButton">
<Border x:Name="Background"
Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}">
<ContentPresenter
x:Name="contentPresenter"
Content="{TemplateBinding Content}"
ContentTemplate="{TemplateBinding ContentTemplate}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
Margin="{TemplateBinding Padding}"/>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
注意在模板绑定中使用额外的CornerRadius
属性。当然,现在您可以切换回混合模式,将此控件添加到曲面并在样式上获得创意。