2011-08-22 91 views
1

我試圖將數據值綁定到附加屬性。但是,它只是沒有得到它的工作。WP7:綁定到附加屬性

我定義它想:

public static class MyClass 
{ 
    public static readonly DependencyProperty MyPropertyProperty = 
     DependencyProperty.RegisterAttached("MyProperty", typeof(string), 
     typeof(MyClass), new PropertyMetadata(null)); 

    public static string GetMyProperty(DependencyObject d) 
    { 
     return (string)d.GetValue(MyPropertyProperty); 
    } 

    public static void SetMyProperty(DependencyObject d, string value) 
    { 
     d.SetValue(MyPropertyProperty, value); 
    } 
} 

現在我用它的XAML看起來是這樣的:

<TextBlock local:MyClass.MyProperty="{Binding MyStringValue}" /> 

我在SetMyProperty方法設置斷點,但它永遠不會被調用。它不會產生任何錯誤,它從來沒有設置或要求。但是,如果我將XAML中的值更改爲固定字符串,它會被調用:

<TextBlock local:MyClass.MyProperty="foobar" /> 

我在想什麼?

注:上面的例子中是最小的版本,顯示了同樣的奇怪的行爲。當然,我的實際實施比這更有意義。

在此先感謝您的任何提示!

+1

AFAIR倍率即使get/set方法是必要的WPF/Silverlight可能不會直接調用它們。這就是爲什麼你的斷點沒有命中,因爲WPF/Silverlight使用反射(只是猜測)或直接使用SetValue。你說它不起作用,值是正確的,但是你的斷點沒有被擊中?然後它就是正常的。抱歉,無法在MSDN中找到此源,但我知道我在某處閱讀它。 – dowhilefor

+0

@dowhilefor:這是有道理的。我只是爲我尋找卻沒有發現這事...... –

+0

有你的get/set聲明一個錯誤,應該是: 回報(字符串)d.GetValue(MyPropertyProperty); – cunningdave

回答

4

而且不會綁定曾經觸發您SetMyProperty - 如果你需要控制好了當值的變化,你必須使用的PropertyMetadata期望一個「變」 -Handler



... new PropertyMetadata(
    null, 
    new PropertyChangedCallback((sender, e) => { 
     var myThis = (MyClass)sender; 
     var changedString = (string)e.NewValue; 
     // To whatever you like with myThis (= the sender object) and changedString (= new value) 
    }) 

+0

太棒了,工作。非常感謝! –

0

將SetMyProperty中的第二個參數的類型更改爲Object類型。

你將獲得一個綁定的對象,而不是字符串,因爲沒有價值。

+0

感謝您的回覆。剛剛嘗試過,但它仍然無法正常工作。 –

+0

這是錯誤的。你永遠不會得到一個Binding對象,他的dp是字符串類型,所以SetMyPropert應該期望一個字符串。 WPF/silverlight將會跟蹤如何和何時評估綁定以獲得dp或ap的有效值。 – dowhilefor