2010-02-07 112 views
0

爲了設置一個類的常規屬性我創建附加的行爲:附加屬性和綁定

public class LookupHelper 
{ 
    public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.RegisterAttached("ItemsSource", typeof(object), typeof(LookupHelper), new UIPropertyMetadata(null, OnItemsSourceChanged)); 

    private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var control = d as MyControl; 
     if(control == null) 
       return; 

     control.ItemsSource = (IEnumerable)e.NewValue; 
    } 

    public static object GetItemsSource(GridColumn column) 
    { 
     return column.GetValue(ItemsSourceProperty); 
    } 

    public static void SetItemsSource(GridColumn column, object value) 
    { 
     column.SetValue(ItemsSourceProperty, value); 
    } 
} 

在這裏,MyControl ItemsSource屬性是一個普通的屬性,所以我不能將其綁定Xaml,因此這個附加行爲。

現在,當我使用這個附加屬性使用字符串或對象它的作品和我設置的斷點被擊中,但是當我用綁定標記設置它時,它永遠不會運行。爲什麼這不起作用?

<MyControl ctrl:LookupHelper.ItemsSource="DataSource"/>; //It works 
<MyControl ctrl:LookupHelper.ItemsSource="{Binding Path=MyDataSource}"/>; //Does not work 

我需要做的是將ItemsSource屬性設置爲綁定指定的值。

+0

你在哪裏設置斷點?什麼方法/線路在您認爲應該調用的時候不被調用? – 2010-02-07 12:27:13

+0

您是否嘗試過使用'Binding'的'Source'屬性而不是'Path'? (你需要指定源爲'StaticResource') – mg007 2010-02-07 13:28:34

回答

3

在您的Get和Set方法中,您將接收對象定義爲GridColumn,它應該是DependencyObject。

您可能也希望將DP的類型從對象更改爲IEnumerable,因爲您將其轉換爲更改處理程序中的DP類型。

-1

您可以發佈您使用的標記嗎?另外,如果實際屬性存在於一個對象上並且在那裏有意義,那麼我認爲您應該在該對象上使用常規依賴屬性,而不是輔助類的附加屬性。

編輯 從MSDN: 爲GetPropertyName訪問的簽名必須是:

public static object GetPropertyName(object target) 

,爲setPropertyName方法訪問的簽名必須是:

public static void SetPropertyName(object target, object value) 

在你的情況,是GridColumn的正確的目標類型?