Declaring Empty String in XAML

03 Jun 2009

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.