Passing parameters to a template

只谈情不闲聊 提交于 2019-12-10 10:26:14

问题


Say I have defined a button with rounded corners.

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

I it possible that the user of this button can specify the CornerRadius? Can I use a TemplateBinding? But where should I bind to? (to Tag?)


回答1:


In order to use a TemplateBinding, there must be a property on the templated control (Button, in this case). Button does not have a CornerRadius or equivalent property, so your options are:

  • hard code the value in the template
  • Hijack another property (such as Tag) to store this information. This is quicker, but lacks type safety, is harder to maintain, and prevents other uses of that property.
  • Subclass Button and add the propery you need, then provide a template for that subclass. This takes a little longer but yields a much nicer experience for consumers of your control.



回答2:


In addition to Kent's suggestions, you could also create an attached property to define the CornerRadius on the button, and bind to that property in the template




回答3:


The button type doesn't have a property for CornerRadius, so templating this won't be possible. I think the easiest way is creating a new class which inherits from Button and add a new dependency property for the CornerRadius. Like this:

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

In xaml you can use it like:

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

A template binding to the CornerRadius will work without a problem now.



来源:https://stackoverflow.com/questions/1031196/passing-parameters-to-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!