如何为从dependencyobject派生的类型的依赖项属性设置默认值
本文关键字:依赖 属性 设置 默认值 类型 dependencyobject 派生 | 更新日期: 2023-09-27 18:02:38
我是WPF的新手,这是我的第一篇文章。我创建了一个名为"Fruit"的类,它源自"DependencyObject",并添加了一个额外的名为"Apple"的属性。我创建了一个新的自定义控件,其中包括一个名为"MyFruit"的依赖属性,类型为"水果"。我的问题是,我如何设置"MyFruit"对象内属性(即"Apple"属性(的默认值?我想使用该对象在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
在依赖属性元数据中插入而不是null
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"));
您需要像这样使用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));
}
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>