2010-09-29 70 views
0

這裏是問題:我如何知道某個類型是否附有字符串轉換器?

我有一個特定對象的屬性。該屬性是類型t。我需要找出,如果一個字符串值可以附加到此屬性。

例如:我有一個Windows.Controls.Button的實例。我需要一個機制,它將返回true爲Button.Background屬性,但Button.Template爲false。

任何人都可以幫忙嗎?非常感謝

+0

'Button'沒有按沒有背景屬性......你的意思是「Text」屬性嗎? – 2010-09-29 13:36:27

+0

好吧,忘了Button - 以網格爲例。當您將字符串值「#00556677」傳遞給它的背景屬性時,它將轉換爲畫筆。但是你不能將一些字符串值傳遞給它的Template屬性。這就是我需要找出任何物體的任何屬性。 – Gal 2010-09-29 14:16:08

回答

1

我覺得你拿錯了方向的問題:

酒店不直接接受字符串:其實財產轉換爲好如果存在轉換器,請鍵入。

然後,你可以看看,如果存在轉換器使用此代碼:

public static bool PropertyCheck(Type theTypeOfTheAimedProperty, string aString) 
{ 
    // Checks to see if the value passed is valid. 
    return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty)) 
      .IsValid(aString); 
} 

這些頁面可能會感興趣太:

  1. http://msdn.microsoft.com/en-us/library/aa970913.aspx
  2. http://msdn.microsoft.com/en-us/library/system.componentmodel.typeconverter.aspx
+0

非常感謝 - 這指出了我一個很好的方向,但我需要的確切代碼是這樣的: return TypeDescriptor.GetConverter(typeof(theTypeOfTheAimedProperty))。CanConvertFrom(typeof(String)); – Gal 2010-09-30 07:03:35

+0

不錯!有很多的樂趣:-) – 2010-09-30 07:54:32

0
public static bool PropertyCheck(this object o, string propertyName) 
{ 
    if (string.IsNullOrEmpty(propertyName)) 
     return false; 
    Type type = (o is Type) ? o as Type : o.GetType(); 

    PropertyInfo pi = type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty); 

    if (pi != null && pi.PropertyType == typeof(string)) 
     return true; 

    return false; 
} 

,然後調用它像這樣:

object someobj = new Object(); 
if (someobj.PropertyCheck("someproperty")) 
    // do stuff 

或者你可以做這樣的:

Type type = typeof(someobject); 
if (type.PropertyCheck("someproperty")) 

這有一定的侷限性,你再不能檢查Type爲屬性鍵入自己的名字,但如果需要的話,你可以隨時創建另一個版本。

我想這是你想要的東西,希望它有助於

+0

此示例對所有屬性都返回true,其類型爲字符串。這不完全是我需要的。我需要找出所有的屬性,其值可以通過字符串在XAML中設置。看看我在之前發佈的背景和模板中給出的例子。無論如何感謝反應 – Gal 2010-09-29 14:29:05

相關問題