【问题标题】:Passing parameters to a template将参数传递给模板
【发布时间】:2009-06-23 07:57:14
【问题描述】:

假设我定义了一个圆角按钮。

<Style x:Key="RoundButton" TargetType="Button">
    <!-- bla bla -->
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border CornerRadius="0,5,5,0" />
                <!-- bla bla -->
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我有可能这个按钮的用户可以指定 CornerRadius 吗?我可以使用模板绑定吗?但是我应该绑定到哪里? (标记?)

【问题讨论】:

    标签: c# .net wpf xaml controltemplate


    【解决方案1】:

    除了 Kent 的建议之外,您还可以创建一个附加属性来定义按钮上的 CornerRadius,并在模板中绑定到该属性

    【讨论】:

      【解决方案2】:

      为了使用TemplateBinding,模板化控件上必须有一个属性(在本例中为Button)。 Button 没有 CornerRadius 或等效属性,因此您的选择是:

      • 硬编码模板中的值
      • 劫持另一个属性(例如Tag)来存储此信息。这更快,但缺乏类型安全性,更难维护,并且阻止了该属性的其他用途。
      • 子类Button 并添加您需要的属性,然后为该子类提供模板。这需要更长的时间,但会为您控制的消费者带来更好的体验。

      【讨论】:

        【解决方案3】:

        按钮类型没有 CornerRadius 的属性,因此无法进行模板化。我认为最简单的方法是创建一个继承自 Button 的新类并为 CornerRadius 添加一个新的依赖属性。像这样:

        using System.Windows;
        using System.Windows.Controls;
        
        namespace WpfApplication3
        {
            public class RoundedButton:Button
            {
                public CornerRadius CornerRadius
                {
                    get { return (CornerRadius) GetValue(CornerRadiusProperty); }
                    set { SetValue(CornerRadiusProperty, value); }
                }
                public static readonly DependencyProperty CornerRadiusProperty =
                    DependencyProperty.Register("CornerRadius", typeof (CornerRadius), 
                    typeof (RoundedButton), new UIPropertyMetadata());
            }
        }
        

        在 xaml 中你可以像这样使用它:

        <Local:RoundedButton 
            Style="{DynamicResource RoundButton}" 
            Width="64" Height="32" 
            Content="Hello" 
            CornerRadius="1,5,10,5" 
            Background="#FF9CFFD5" />     
        

        绑定到 CornerRadius 的模板现在可以正常工作了。

        【讨论】:

        • 我遇到了您建议的方法的问题。如果您将 CornerRadius 设置为 RoundButton 样式,它将不会应用于按钮。
        猜你喜欢
        • 2015-09-22
        • 1970-01-01
        • 1970-01-01
        • 2018-04-05
        • 2010-12-26
        • 2016-12-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多