c# - UWP - C# XAML - 如何在 DependencyProperty 中施加约束?
问题描述
在面向对象编程中,对象以最高权限管理自己的属性,并通过它们的正式接口与其他对象进行通信。这就是封装原理。对于普通属性,有 Getters/Setters。
对于 setter 中的允许值,对象可以施加约束。例如,此类将不允许 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 ;
}
使用这种方法,在回调方法中我可以检查正在发生的事情,我可以同时检查旧值和新值。但是有了这个我只能检查新值,但不能限制或禁止新值。
如何对属性可能具有的值施加限制?
解决方案
正如您在示例中看到的那样,您可以过滤 Age 中的数据并仅在满足条件时才Setter
调用该方法。SetValue()
public int Age
{
get { return (int)GetValue(AgeProperty); }
set
{
if (value < 0)
{
// throw error or other things
}
else
{
SetValue(AgeProperty, value);
}
}
}
但是如果要根据 .xml 来调整绑定这个属性的控件,Age
可以考虑使用IValueConverter
.
这是文件。
此致。
推荐阅读
- css - bootswatch 中的 CSS 样式不适用于 Shiny R
- mongodb - 这个奇怪的 BSON 日期保存是怎么回事?
- android - 为什么使用接口适配器 Activity 时出现 ClassException?
- environment-variables - 如何在 GitLab Omnibus 配置中使用环境变量
- vb.net - 在表单关闭时关闭特定应用程序
- react-native - 尝试从 expo 中的 react-native-appearance 导入时,Null 不是对象
- amazon-web-services - 不使用 EKS 时,我们可以在 AWS 的 Kubernetes 集群上使用 AWS VPC CNI
- python-3.x - 使用从 txt 文件中的列表中获取的变量写入文件
- css - 如何在背景图像上粘贴 div?
- python - 如何在 linux ubuntu 18.04 python 3.7 上使用 pip 安装 venv