首页 > 解决方案 > 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 ;
    }

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

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

标签: c#oopuwpuwp-xaml

解决方案


正如您在示例中看到的那样,您可以过滤 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.

这是文件

此致。


推荐阅读