UWP - C# XAML - 如何在依赖项属性中施加约束?



在面向对象编程中,对象使用最高权限管理自己的属性,并通过其形式接口与其他对象进行通信。这就是封装原理。对于普通属性,有 Getters/Setters。

对象可以对资源库中允许的值施加约束。例如,此类不允许 Age 属性的值小于 0 或大于 150:

Class person
{
public string Name {get; set;}
private int age;
public int Age 
{
get => age;  
set
{
if (value<0) throw new ArgumentException("no one can have negative age! you ape!");
if (value>150) throw new ArgumentException("master Yoda's profile 
should be loaded in the Galactic Empire database (currently developed by Mocrisoft)");
age = value;
} 
}
}

现在,假设 Person 类是一个 DependencyObject(它继承自 DependencyObject(,我想公开一个 DepedencyProperty,并让对象的这个属性成为其他对象属性的从属。因此,年龄属性如下所示:

public int Age
{
get { return (int)GetValue(AgeProperty); }
set { SetValue(AgeProperty, value); }
}
// Using a DependencyProperty as the backing store for Age.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty AgeProperty =
DependencyProperty.Register("Age", typeof(int), typeof(Person), new PropertyMetadata(0, callback));
private static void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// inspect changed triggered by other object ;
}

使用这种方法,在回调方法中,我可以检查正在发生的事情,我可以检查旧值和新值。但是有了这个,我只能检查新值,而不能限制或禁止新值。

如何对属性可以具有的可能值施加限制?

我不使用 UWP,但我认为您在这里描述的术语是验证。

https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/dependency-property-callbacks-and-validation

似乎存在 的过载。接受验证器的 Register((。 你可能会做这样的事情

public static readonly DependencyProperty AgeProperty = DependencyProperty.Register(
"Age",
typeof(int),
typeof(Person),
new FrameworkPropertyMetadata(
0,
callback
),
new ValidateValueCallback(IsValidAge)
);

然后


public static bool IsValidAge(object value)
{
int v = (int)value;
return (v > 0 && v < 150);
}

正如您在示例中所看到的,您可以过滤 AgeSetter中的数据,并仅在满足条件时才调用SetValue()方法。

public int Age
{
get { return (int)GetValue(AgeProperty); }
set 
{
if (value < 0)
{
// throw error or other things
}
else
{
SetValue(AgeProperty, value);
}
}
}

但是,如果要根据Age调整在 XAML 中绑定此属性的控件,可以考虑使用IValueConverter

这是文档。

此致敬意。

最新更新