2011-05-10 50 views
4

我想要實現一組類似的附加行爲以用於WPF應用程序。 因爲他們都共享大量的樣板代碼,我不想重複每一個代碼,我想創建一個從它繼承的基本行爲。 但是,由於附加行爲中的所有內容都是靜態的,所以我不知道如何去做。附加行爲的繼承

舉例來說,採取這種行爲,執行上的mousedown的方法(真正的行爲當然會做一些不容易在一個事件處理完成):

public static class StupidBehavior 
{ 
    public static bool GetIsEnabled(DependencyObject obj) 
    { 
     return (bool)obj.GetValue(IsEnabledProperty); 
    } 

    public static void SetIsEnabled(DependencyObject obj, bool value) 
    { 
     obj.SetValue(IsEnabledProperty, value); 
    } 

    // Using a DependencyProperty as the backing store for ChangeTooltip. This enables animation, styling, binding, etc... 
    public static readonly DependencyProperty IsEnabledProperty = 
     DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(StupidBehavior), new UIPropertyMetadata(false, IsEnabledChanged)); 


    private static void IsEnabledChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) 
    { 
     ((UIElement)sender).MouseDown += { (o,e) => MyMethod(); }; 
    } 

    private static void MyMethod() 
    { 
     MessageBox.Show("Boo"); 
    }  
} 

現在,我想創建一種新的行爲,應該有一個不同的MyMethod實現,以及一些控制它的附加屬性。這應該怎麼做?

+3

當孩子繼承'StupidBehavior'時,這總是一種遺憾。 – 2011-05-10 16:34:50

回答

2

您可以創建另一個附屬屬性,其中包含由主行爲作爲子類替換被調用的詳細實現。屬性所持有的對象可能是非靜態的,並且可以像state-object一樣使用。

你也許可以放入一個屬性這個問題,以及,其中property == null意味着關閉

1

你可以使用一個靜態構造函數,形成Dictionary<DependencyProperty,EventHandler>具體DP映射到一個特定的處理程序和使用法DependencyPropertyChanged回調:

static StupidBehavior() 
{ 
    handlerDictionary[IsEnabledProperty] = (o,e) => MyMethod(); 
    handlerDictionary[SomeOtherProperty] = (o,e) => SomeOtherMethod(); 
} 

private static void CommonPropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args) 
{ 
    var uie = sender as UIElement; 
    if (uie != null) 
    { 
     //removing before possibly adding makes sure the multicast delegate only has 1 instance of this delegate 
     sender.MouseDown -= handlerDictionary[args.Property]; 
     if (args.NewValue != null) 
     { 
      sender.MouseDown += handlerDictionary[args.Property]; 
     } 
    } 
} 

或者乾脆做一個args.Propertyswitch。或者介於兩者之間的東西涉及基於DependencyProperty的常用方法和分支。

我不確定爲什麼你的IsEnabled屬性處理DependencyProperty類型的值,而不是像bool那樣會產生更多語義的東西。

+0

謝謝!它確實應該是bool。複製粘貼錯誤=) – Jens 2011-05-11 06:28:33