Monday, June 01, 2009

Declaring Empty String in XAML

Shown below is a code snippet which does not work.

   1: <ListView xmlns:System="clr-namespace:System;assembly=mscorlib">


   2:     <ListView.ItemsSource>


   3:      <coll:ArrayList>


   4:           <System:String></System:String>


   5:           <System:Int32>34</System:Int32>


   6:     </coll:ArrayList>  


   7:     </ListView.ItemsSource>


   8:   </ListView>






One would notice the following error when the above XAML is parsed.



Cannot create object of type “System.String”. CreateInstance failed, which can be caused by not having a public default constructor for ‘System.String’.



The reason for this error is that the “System.String” class does not provide a default constructor and this disallows declaring empty string.



What’s the fix?





   1: <ListView xmlns:System="clr-namespace:System;assembly=mscorlib">


   2:     <ListView.ItemsSource>


   3:      <coll:ArrayList>


   4:             <!-- notice empty string via usage of x:Static -->


   5:           <x:Static Member="System:String.Empty" />          


   6:           <System:Int32>34</System:Int32>


   7:     </coll:ArrayList>  


   8:     </ListView.ItemsSource>


   9:   </ListView>





Hope this helps.

3 comments:

Anonymous said...

You feedburner feed latest entry is from Februrary, yet, your latest post is June. Might want to check on that.

Krishna Bhargava Vangapandu said...

William,

Thank you...I haven't noticed it...Looks like it was the feed size error.

I have fixed it and looks like its working. Thanks again.

Unknown said...

Cool! Thanks.