【问题标题】:UWP - C# XAML - How to impose a constraint in a DependencyProperty?UWP - C# XAML - 如何在 DependencyProperty 中施加约束?
【发布时间】:2019-10-10 14:28:45
【问题描述】:

在面向对象编程中,对象以最高权限管理自己的属性,并通过它们的正式接口与其他对象进行通信。这就是封装原理。对于普通属性,有 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,并让对象的这个属性成为其他对象属性的从属。所以,Age 属性看起来像......:

    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# oop uwp uwp-xaml


    【解决方案1】:

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

    https://docs.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);
    }
    
    

    【讨论】:

    • 感谢您的回复。但这是针对 WPF 的。似乎 UWP 不支持验证
    【解决方案2】:

    如您在示例中所见,您可以过滤 Age 的 Setter 中的数据,并仅在满足条件时才调用 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

    这里是document

    最好的问候。

    【讨论】:

      猜你喜欢
      • 2010-11-09
      • 1970-01-01
      • 2022-08-15
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2015-11-26
      • 1970-01-01
      • 2013-05-08
      相关资源
      最近更新 更多