问题描述
我希望在 .NET Framework 4.7.2 类库中使用 AngelSix 的自定义附加属性 Code。但是,当我尝试向 Xaml 文件中的对象添加附加属性时,我从 Visual Studio 中的 Intellisense 获得的是 local:BaseAttachedProperty`2.value
而不是所需的附加属性,如 local:IsBusyProperty.Value
。当我手动键入 local:IsBusyProperty.Value
时,应用程序崩溃,错误消息 The method or operation is not implemented
指向附加属性。
我知道 `2
表示泛型类型,带有 2 个泛型参数 - 暗指带有两个泛型参数的基类:
public abstract class BaseAttachedProperty<Parent,Property>
where Parent : new(){}
但是我如何获得正确的附加属性,即使用泛型参数实现基类而不是这个神秘的 local:BaseAttachedProperty`2.value
消息的类?
如果我在不继承 BaseAttachedProperty 的情况下创建附加属性,则一切正常。
German Forum 上的一位用户遇到了同样的问题,并写道他可以使用 xmlns:
来获取附加属性,但这对我不起作用!
这是 AngelSix 提供的示例。它对我不起作用。
public class IsBusyProperty : BaseAttachedProperty<IsBusyProperty,bool>
{
}
这是我的代码:
public class IsBusyProperty
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Registerattached("Value",typeof(bool),typeof(IsBusyProperty),new PropertyMetadata(false));
public static bool GetValue(DependencyObject obj)
{
return (bool)obj.GetValue(ValueProperty);
}
public static void SetValue(DependencyObject obj,bool value)
{
obj.SetValue(ValueProperty,value);
}
}
<Button Content="Login"
IsDefault="True"
local:BaseAttachedProperty`2.Value="{Binding LoginIsRunning}" <-- Here is the trouble area
Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=Page}"
HorizontalAlignment="Center" />
<Button Content="Login"
IsDefault="True"
local:IsBusyProperty.Value="{Binding LoginIsRunning}"
Command="{Binding LoginCommand}"
CommandParameter="{Binding ElementName=Page}"
HorizontalAlignment="Center" />
解决方法
我从未使用过您链接到的代码,但从我所见,我认为您误解了它的用途。让我把你的注意力带回到你引用的这段代码上:
public class IsBusyProperty : BaseAttachedProperty<IsBusyProperty,bool>
{
}
这不是您应该填写的示例,它实际上是您可以使用的功能齐全的附加属性。它为空的原因是您需要的所有代码都已经在基类 BaseAttachedProperty
中。
您确实需要导入正确的 xmlns
(XML 命名空间)才能使用它,这将是定义 IsBusyProperty
类的命名空间。如果你想使用 Fasetto.Word 库中已经定义的那个,代码可能是:
xmlns:fas="clr-namespace:Fasetto.Word;assembly=Fasetto.Word"
...
<Button fas:IsBusyProperty.Value="{Binding LoginIsRunning}"/>
我不能 100% 确定 assembly=Fasetto.Word
部分是否正确,但是如果您开始输入 xmlns:fas="clr-namespace:Fasetto.Word
,Visual Studio 应该会告诉您正确的值是什么。 fas
只是我从库名称的前 3 个字母中挑选的一个随意名称,但只要您一直保持一致,您就可以使用任何名称。有关 xmlns
的更多信息,请查看 MSDN article。
如果您想使用 BaseAttachedProperty
创建自己的附加属性,您可以这样做:
public class SomeOtherProperty : BaseAttachedProperty<SomeOtherProperty,TypeOfProperty>
{
}
然后你会像这样使用它:
<Button yourns:SomeOtherProperty.Value="{Binding Something}"/>
其中 yourns
是您定义 xmlns
的任何命名空间的 SomeOtherProperty
。