2011-12-02 67 views
2

我試圖使用附加屬性爲我的數據對象添加一些表示邏輯。 我即將切換到包裝,但我很好奇爲什麼以下不適合我。 表示邏輯類代碼:Silverlight。綁定到數據對象的附加屬性,不會輸入獲取器

public static readonly DependencyProperty TestPropProperty = DependencyProperty.RegisterAttached(
     "TestProp", 
     typeof(string), 
     typeof(DataClassPresenter), 
     new PropertyMetadata("[Test]") 
     ); 

    public static string GetTestProp(DataClass el) 
    { 
     return "Haha"; // (string)el.GetValue(TestPropProperty); 
    } 

    public static void SetTestProp(DataClass el, string val) 
    { 
     el.SetValue(TestPropProperty, val); 
    } 

我結合屬性值的XAML是:

 <TextBlock Text="{Binding Path=(prz:DataClassPresenter.TestProp), StringFormat='Depend:\{0\}'}"/> 

它的工作原理,但始終顯示「[測試]」,「哈哈」永遠不會回來了, GetTestProp從不輸入。 我在做什麼錯?

回答

3

這是因爲你的get方法不能保證被調用。 Silverlight(和WPF)可以單獨使用DependencyProperty獲取或設置屬性值。你不應該在get或set方法中引入任何邏輯。

此外,您不應該使用DataClass作爲參數。傳遞的對象將是您要設置附加屬性的元素,在您的示例中它是一個TextBlock。所以你應該接受DependencyObjectUIElement而不是DataClass

+0

奇怪。如果沒有這些方法,它就完全拒絕綁定,並且與他們在一起,他們不會進入。 –

+0

@IgorBe - 是的,它將使用方法來查看屬性是否適用於給定元素,因此它們必須存在。我注意到你的代碼有其他問題(並更新了我的答案),但是不管怎樣,你都不應該在你的方法中引入邏輯。 – CodeNaked