为什么我的自定义控件无法正常工作?

时间:2018-05-13 08:27:40

标签: wpf xaml

我为自定义按钮创建了一个自定义控件,这是它的类:

public class SButton : Button
    {
        static SButton()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(SButton), new FrameworkPropertyMetadata(typeof(SButton)));
        }

        public Brush PressBackground
        {
            get { return (Brush)GetValue(PressBackgroundProperty); }
            set { SetValue(PressBackgroundProperty, value); }
        }

        // Using a DependencyProperty as the backing store for PressBackground.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty PressBackgroundProperty =
            DependencyProperty.Register("PressBackground", typeof(Brush), typeof(SButton), null);


    }

这是Generic.xaml:

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SealBase">
    <Style TargetType="{x:Type local:SButton}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type local:SButton}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" VerticalAlignment="{TemplateBinding VerticalAlignment}" HorizontalAlignment="{TemplateBinding HorizontalAlignment}" Background="{TemplateBinding Background}" Name="B">
                        <TextBlock FontSize="{TemplateBinding FontSize}" Foreground="{TemplateBinding Foreground}" FontFamily="{TemplateBinding FontFamily}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}">
                        <ContentPresenter></ContentPresenter>
                        </TextBlock>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsPressed" Value="true">
                            <Setter Property="Background" TargetName="B" Value="{Binding PressBackground, RelativeSource={RelativeSource Self}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

当我在XAML中使用SButton时:

<CustomControl:SButton PressBackground="Black" Background="Red" Content="555" Foreground="White"/>

自定义控件无错误地工作,但是当我按下它时,颜色不会变为黑色。

这有什么关系?请你帮我吗?谢谢你。

1 个答案:

答案 0 :(得分:4)

TemplateBinding有限,在模板触发器中不起作用。另一种方法是使用TemplatedParent相对来源

Value="{Binding PressBackground, RelativeSource={RelativeSource TemplatedParent}}"