gpt4 book ai didi

wpf - 限制附加依赖属性范围的约束

转载 作者:行者123 更新时间:2023-12-03 23:38:12 24 4
gpt4 key购买 nike

有没有办法向附加的依赖属性添加约束,以便它只能应用于特定类型,即元数据中的某些内容?

如果不是,显式键入附加 DP 的静态获取和设置方法是否有意义?

示例:

例如,如果我有以下声明:

public static int GetAttachedInt(DependencyObject obj) {
return (int)obj.GetValue(AttachedIntProperty);
}

public static void SetAttachedInt(DependencyObject obj, int value) {
obj.SetValue(AttachedIntProperty, value);
}

public static readonly DependencyProperty AttachedIntProperty =
DependencyProperty.RegisterAttached("AttachedInt", typeof(int),
typeof(Ownerclass), new UIPropertyMetadata(0));

将其更改如下是否有意义,仅将其应用于文本框?
public static int GetAttachedInt(TextBox textBox) {
return (int)textBox.GetValue(AttachedIntProperty);
}

public static void SetAttachedInt(TextBox textBox, int value) {
textBox.SetValue(AttachedIntProperty, value);
}

public static readonly DependencyProperty AttachedIntProperty =
DependencyProperty.RegisterAttached("AttachedInt", typeof(int),
typeof(Ownerclass), new UIPropertyMetadata(0));

我的问题是,因为这会导致不一致,因为 GetValue 和 SetValue 可以再用于任何类型,并且在标记中也不可能限制附件。

我以前所做的是在 PropertyChanged 处理程序中添加了一个异常,并在那里引发了一个仅允许 xy 类型的异常。

你怎么认为?

最佳答案

我相信为了限制附加属性的目标类型,您需要做的就是更改 GetPropertyName 的定义。和 SetPropertyName方法。

例子:

public static int GetAttachedInt(MyTargetType obj)
{
return (int)obj.GetValue(AttachedIntProperty);
}

public static void SetAttachedInt(MyTargetType obj, int value)
{
obj.SetValue(AttachedIntProperty, value);
}

哪里 MyTargetType可以是从 DependencyObject 继承的任何类型.

关于wpf - 限制附加依赖属性范围的约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3279718/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com