[英]Using Custom Attached Properties with Base Class and Generics
我希望在 .NET Framework 4.7.2 class 庫中使用 AngelSix 的自定義附加屬性代碼。 但是,當我嘗試將附加屬性添加到 Xaml 文件中的 object 時,我從 Visual Studio 中的 Intellisense 得到的是local:BaseAttachedProperty`2.value
而不是所需的附加屬性,如local:IsBusyProperty.Value
。 當我手動鍵入local:IsBusyProperty.Value
時,應用程序崩潰並顯示錯誤消息The method or operation is not implemented
指向附加屬性。 我了解`2
表示具有 2 個泛型參數的泛型類型 - 暗指帶有兩個泛型參數的 Base Class:
public abstract class BaseAttachedProperty<Parent, Property>
where Parent : new(){}
但是如何獲得正確的附加屬性,即使用通用參數實現基本 class 而不是這個神秘local:BaseAttachedProperty`2.value
消息的類?
如果我創建一個附加屬性而不從 BaseAttachedProperty 繼承,一切正常。
德國論壇上的一位用戶也遇到了同樣的問題,並寫道他可以使用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>
{
}
這不是您應該填寫的示例,它實際上是您可以使用的功能齊全的附加屬性。 它為空的原因是因為您需要的所有代碼都已經在基礎 class BaseAttachedProperty
。
您確實需要導入正確的xmlns
(XML 命名空間)才能使用它,這將是定義IsBusyProperty
class 的命名空間。 如果您想使用已在 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
fas
Visual Studio 應該會告訴您正確的值是什么。fas 只是一個abritrary name 我從庫名稱的前 3 個字母中選擇,但您可以使用任何名稱,只要您是一致的。有關xmlns
的更多信息,請查看MSDN 文章。
如果您想使用BaseAttachedProperty
創建自己的附加屬性,您可以執行以下操作:
public class SomeOtherProperty : BaseAttachedProperty<SomeOtherProperty, TypeOfProperty>
{
}
然后你會像這樣使用它:
<Button yourns:SomeOtherProperty.Value="{Binding Something}"/>
其中yourns
是您在其中定義SomeOtherProperty
的任何命名空間的xmlns
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.