2013-11-04 176 views
4

我試圖從Button的ContentTemplate綁定到附加屬性。我閱讀所有類似於「綁定到附加屬性」的問題的答案,但我沒有解決問題的運氣。綁定到附加屬性

請注意,此處介紹的示例是我的問題的簡化版本,以避免混淆業務代碼問題。

所以,我確實有附加屬性的靜態類:

using System.Windows; 

namespace AttachedPropertyTest 
{ 
    public static class Extender 
    { 
    public static readonly DependencyProperty AttachedTextProperty = 
     DependencyProperty.RegisterAttached(
     "AttachedText", 
     typeof(string), 
     typeof(DependencyObject), 
     new PropertyMetadata(string.Empty)); 

    public static void SetAttachedText(DependencyObject obj, string value) 
    { 
     obj.SetValue(AttachedTextProperty, value); 
    } 

    public static string GetAttachedText(DependencyObject obj) 
    { 
     return (string)obj.GetValue(AttachedTextProperty); 
    } 

    } 
} 

和窗口:

<Window x:Class="AttachedPropertyTest.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     xmlns:local="clr-namespace:AttachedPropertyTest" 
     Title="MainWindow" Height="350" Width="525"> 
    <Grid> 
    <Button local:Extender.AttachedText="Attached"> 
     <TextBlock 
     Text="{Binding 
      RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}, 
      Path=(local:Extender.AttachedText)}"/> 
    </Button> 
    </Grid> 
</Window> 

這幾乎是它。我希望看到按鈕中間的「附加」。 相反,它會崩潰:屬性路徑無效。 'Extender'沒有名爲'AttachedText'的公共屬性。

我對SetAttachedText和GetAttachedText設置斷點,SetAttachedText 是執行,所以其附加到按鈕的作品。 GetAttachedText從不執行,所以在解析時它不會找到屬性。我的問題其實更復雜(我試圖從App.xaml中的Style內部進行綁定),但讓我們從簡單的一個開始吧。

我錯過了什麼嗎? 謝謝,

回答

5

您附加的財產註冊是錯誤的。 所有者類型Extender,而不是DependencyObject

public static readonly DependencyProperty AttachedTextProperty = 
    DependencyProperty.RegisterAttached(
     "AttachedText", 
     typeof(string), 
     typeof(Extender), // here 
     new PropertyMetadata(string.Empty)); 

參見RegisterAttached MSDN文檔:

ownerType - 即正在註冊依賴屬性僱主類型

+0

燁。我認爲(錯誤地)ownerType是屬性可以附加到的類型。謝謝。 –