给自定义WPF控件添加属性?

12

今天早上我刚开始学习WPF,所以这可能是一个容易解决的问题。我从创建一个具有渐变背景的按钮开始。我想在控件的属性中声明渐变开始和结束颜色,然后在模板中应用它们。但是,我在编译代码时遇到了一些问题。异常提示告诉我该属性不可访问,但当我将可见性修饰符更改为public时,它又抱怨找不到静态属性...

以下是我的XAML代码:

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="my:GradientButton">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type my:GradientButton}">
                        <Grid>
                            <Ellipse Width="{TemplateBinding Width}" Height="{TemplateBinding Height}" Stroke="{TemplateBinding Foreground}" VerticalAlignment="Top" HorizontalAlignment="Left">
                                <Ellipse.Fill>
                                    <LinearGradientBrush>
                                        <GradientStop Color="{TemplateBinding GradientStart}" Offset="0"></GradientStop><!--Problem on this line!!!-->
                                        <GradientStop Color="{TemplateBinding GradientEnd}" Offset="1"></GradientStop>
                                    </LinearGradientBrush>
                                </Ellipse.Fill>
                            </Ellipse>
                            <Polygon Points="18,12 18,38, 35,25" Fill="{TemplateBinding Foreground}" />
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </StackPanel.Resources>
    <my:GradientButton x:Name="btnPlay" Height="50" Width="50" Foreground="Black" Click="Button_Click" GradientStart="#CCCCCC" GradientEnd="#7777777" />
</StackPanel>

这是我的自定义控件的代码:

public class GradientButton : Button
{
    static DependencyProperty GradientStartProperty;
    static DependencyProperty GradientEndProperty;

    static GradientButton()
    {
        GradientStartProperty = DependencyProperty.Register("GradientStart", typeof(Color), typeof(GradientButton));
        GradientEndProperty = DependencyProperty.Register("GradientEnd", typeof(Color), typeof(GradientButton));
    }

    public Color GradientStart
    {
        get { return (Color)base.GetValue(GradientStartProperty); }
        set { base.SetValue(GradientStartProperty, value); }
    }

    public Color GradientEnd
    {
        get { return (Color)base.GetValue(GradientEndProperty); }
        set { base.SetValue(GradientEndProperty, value); }
    }
}

编辑: 这是我收到的设计时异常

Cannot reference the static member 'GradientStartProperty' on the type 'GradientButton' as it is not accessible.
1个回答

14

我明白了...这个:

static DependencyProperty GradientStartProperty; 
static DependencyProperty GradientEndProperty;

需要更改为这个:

public static DependencyProperty GradientStartProperty; 
public static DependencyProperty GradientEndProperty;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接