【问题标题】:Bind template property value to templated control property将模板属性值绑定到模板化控件属性
【发布时间】:2011-04-15 13:10:07
【问题描述】:

标题有点模糊,问题是:

我正在通过用我自己的模板交换模板来实现 Silverlight 4 按钮。是否可以将边框角半径绑定到按钮高度?

例如用户可以在设计器中设置高度为30,则模板内边框的圆角半径应为15。当高度为50时,圆角半径应为25等

如果可能,我需要一个纯 XAML 解决方案。

谢谢

【问题讨论】:

    标签: silverlight templates custom-controls expression-blend


    【解决方案1】:

    这不是纯 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));
        }
    
    }
    

    在themes/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 属性的使用。当然,现在您切换回混合,将此控件添加到表面并在样式上发挥创意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-15
      • 1970-01-01
      相关资源
      最近更新 更多