2013-03-05 70 views
0

我有一個行爲,我想附加到多個控件並基於它們的類型,我想編寫邏輯,爲此我需要確定關聯對象的類型在運行時,我想知道我該怎麼做確定關聯對象的實際運行時類型

class CustomBehavior:Behavior<DependencyObject> 
{ 
    protected override void OnAttached() 
    { 
     base.OnAttached(); 
     if(AssociatedObject.GetType()==typeof(TextBox)) 
     { 
      //Do Something 
     } 

     else if(AssociatedObject.GetType()==typeof(CheckBox)) 
     { 
      //Do something else 
     } 
//.... 
//... 
     else 
      //Do nothing 
    } 
} 

這項工作?

回答

0

我喜歡:

if(typeof(TextBox).IsAssignableFrom(AssociatedObject.GetType())) 
{ 
    ...etc 
} 

這會爲TextBox工作,並從它派生的類。

備註:如果打算將這種行爲用於控件(TextBox,ComboBox等),最好將其更改爲Behavior<FrameworkElement>。通過這種方式,您可以訪問FrameworkElement(I.E L.I.F.E)的所有常用功能,而無需轉換爲特定類型。

1

你可以使用關鍵字is,這將皮卡的類型和派生類型

protected override void OnAttached() 
{ 
    base.OnAttached(); 
    if(AssociatedObject is TextBox) 
    { 
     //Do Something 
    } 

    else if(AssociatedObject is CheckBox) 
    { 
     //Do something else 
    }