wpf 如何为从DependencyObject派生的类型的依赖项属性设置默认值

p5cysglq  于 2023-03-31  发布在  其他
关注(0)|答案(3)|浏览(131)

我是WPF的新手,这是我的第一篇文章。我创建了一个名为“Fruit”的类,它继承自“DependencyObject”,并添加了一个名为“Apple”的额外属性。我创建了一个新的自定义控件,其中包括一个名为“MyFruit”的类型为“Fruit”的依赖属性。我的问题是,我怎么能设置默认值的属性内'MyFruit'对象(即'苹果'属性?我想设置这在XAML使用对象.

public class Gauge : Control
{
    .
    .
    .

    //---------------------------------------------------------------------
    #region MyFruit Dependency Property

    public Fruit MyFruit
    {
        get { return (Fruit)GetValue(MyFruitProperty); }
        set { SetValue(MyFruitProperty, value); }
    }

    public static readonly DependencyProperty MyFruitProperty =
        DependencyProperty.Register("MyFruit", typeof(Fruit), typeof(CircularGauge), null);

    #endregion

} 

//-------------------------------------------------------------------------
#region Fruit class

public class Fruit : DependencyObject
{
    private int apple;

    public int Apple
    {
        get { return apple; }
        set { apple = value; }
    }

 }

#endregion
ghhkc1vu

ghhkc1vu1#

在依赖项属性元数据插入中使用

new UIPropertyMetadata("YOUR DEFAULT VALUE GOES HERE")

所以现在变成了

public static readonly DependencyProperty MyFruitProperty =
    DependencyProperty.Register("MyFruit", typeof(Fruit), typeof(CircularGauge), new UIPropertyMetadata("YOUR DEFAULT VALUE GOES HERE"));
imzjd6km

imzjd6km2#

您需要像这样使用PropertyMetaData

class MyValidation
{
    public bool status
    {
        get { return (bool)GetValue(statusProperty); }
        set { SetValue(statusProperty, value); }
    }
    
    public static readonly DependencyProperty statusProperty = DependencyProperty.Register("status", typeof(bool), typeof(MyValidation),new PropertyMetadata(false));
}
kq0g1dla

kq0g1dla3#

public static readonly DependencyProperty BackgroundColorProperty = DependencyProperty.Register("BackgroundColor", typeof(Brush), typeof(YinaKassaProductButtonCustomControl), new PropertyMetadata(null));

默认值必须是不可变的,因此不能将其设置为其他依赖项属性的值。
我自己最终向我的类添加了一个属性,就像这样

public Brush BorderColor => IsSelectedBorderColor ?? BackgroundColor;

然后我绑定到我的自定义控件的模板中的BorderColor。基本上它检查依赖项属性IsSelectedBorderColor是否不为null并使用其值,否则它使用BackgroundColor依赖项属性的值。
我把它用在扳机上...

<ControlTemplate.Triggers>
    <Trigger Property="IsSelected" Value="True">
        <Setter Property="Background" Value="Transparent"></Setter>
        <Setter Property="Foreground" Value="White"></Setter>
        <Setter Property="BorderBrush" Value="{Binding BorderColor, RelativeSource={RelativeSource Self}}"></Setter>
    </Trigger>
    <Trigger Property="IsSelected" Value="False">
        <Setter Property="Background" Value="{Binding BackgroundColor, RelativeSource={RelativeSource Self}}"></Setter>
        <Setter Property="Foreground" Value="{Binding ForegroundColor, RelativeSource={RelativeSource Self}}"></Setter>
        <Setter Property="BorderBrush" Value="{Binding BackgroundColor, RelativeSource={RelativeSource Self}}"></Setter>
    </Trigger>
</ControlTemplate.Triggers>

相关问题