开发者

Bind template property value to templated control property

The title is a bit fuzzy, the problem is:

I'm implementing a Silverlight 4 button by swapping the template with my own. Is it possible to bind the border corner radius to the button height?

For example the user can set the height in designer to be 30, then the corner radius of the template inner border should be 15. When height is 50, then corner radius should be 25, etc.

If possible, I n开发者_高级运维eed a pure XAML solution.

Thanks


The is no pure Xaml solution. Ultimately you need something to at the very least perform the expression y/2 and that is not something currently offered by any existing Xaml based component.

Open the project in Vs2010. Add a new item... "Silverlight Templated Control" call it "RoundEndedButton".

Replace the source with:-

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));
    }

}

In the themes/Generic.xaml modify its default template. Here is my very simple example:-

<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>

Note the use of the extra CornerRadius property in template binding. Of course now you switch back to blend add this control to a surface and get creative on the style.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜