簡體   English   中英

在Silverlight中綁定到非依賴對象

[英]Binding to a Non Dependency Object in Silverlight

我在xaml中有一個聲明如下:

<my:CMIconText Icon="Attachment" Text="Logo" />

其中CMIconText是來自abc.Core.dll的類,而Text是該類中的字符串屬性。

我想使用靜態綁定來綁定文本,但是由於“文本”不是依賴項屬性,因此我無法這樣做。 問題是我無法將其作為依賴項屬性,因為abc.Core.dll被多個其他項目使用。

還有其他替代方法,可以在不更改dll的情況下綁定屬性?

謝謝,

阿卜迪

您可以在對象上使用附加的依賴項屬性來監視綁定並將該值靜態傳遞給您的CMIconText對象。 與OneWay綁定一起使用時效果更好,但是可以進行雙向綁定。

public class TextBoxExtension
{
    public static readonly DependencyProperty AttachedTextProperty;

    static TextBoxExtension()
    {
        AttachedTextProperty = DependencyProperty.RegisterAttached("AttachedText", typeof (string), typeof (TextBoxExtension), new PropertyMetadata(default(string), TextAttachedChanged));
    }

    public static string GetAttachedText(TextBox sender)
    {
        return (string) sender.GetValue(AttachedTextProperty);
    }

    public static void SetAttachedText(TextBox sender, string value)
    {
        sender.SetValue(AttachedTextProperty, value);
    }

    private static void TextAttachedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
    {
        ((TextBox) sender).Text = e.NewValue as string;
    }
}

這將允許您在XAML中執行此操作:

<TextBox Grid.Row="0" Grid.Column="1" controls:TextBoxExtension.AttachedText="{Binding Name}" />

這比重新實現整個類要簡單得多。 當然,您需要將TextBox的引用更改為您自己的對象。 但是因為我沒有它,所以它是我可以給您舉個例子的最接近的例子。

我將創建一個單獨的類,該類具有相似的屬性和行為,但在需要時具有依賴項屬性。 您可能希望它擴展CMIconText (特別是如果您可以重寫Text屬性以提供新的實現;即使將base屬性更改為DP沒有意義,也許您可​​以將其修改為virtual ) 。 如果不能使基本Textvirtual我將避免擴展該類。 在那種情況下,我將使類完全分離,並使用適當的方法(或AutoMapper )從/向CMIconText進行轉換。

public class SilverlightCMIconText : CMIconText
{
    public override string Text
    {
        get { ... }
        set { ... }
    }
}
<local:SilverlightCMIconText Icon="Attachment" Text="{StaticResource Whatev}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM