簡體   English   中英

將屬性添加到自定義WPF控件?

[英]Adding Properties to Custom WPF Control?

我今天早上剛剛開始WPF,所以這是(希望)一個容易解決的問題。 我開始創建一個具有漸變背景的按鈕。 我想在控件的屬性中聲明漸變開始和結束顏色,然后將它們應用到模板中。 我在編譯代碼時遇到了麻煩。 我得到的例外是xaml告訴我屬性不可訪問但是當我將visiblity修飾符改為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.

我想通了......這個:

static DependencyProperty GradientStartProperty; 
static DependencyProperty GradientEndProperty;

需要改為:

public static DependencyProperty GradientStartProperty; 
public static DependencyProperty GradientEndProperty;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM