Binding to a list of strings in XAML for Windows 8 Apps

I came across and odd problem in my work today when binding to a list of strings. I was developing an application where I had a need to bind to a List of strings, where each string would be the contents of a TextBox. This in itself was not an issue. However sometimes the List of strings would contain an empty string. This caused an odd behaviour where the Text value of my TextBox was instead bound to the parent DataContext of the DataContext I wished to bind to. I do not know whether this is intended behaviour or a bug, as I could not find any examples of this when I searched on Google for my issue.

The Issue

My situation was simple. I had a ViewModel that contained a list of strings. I was using a DataTemplate inside of an ItemsControl that was bound to my list of strings. The DataTemplate contained a TextBox bound to the parent using the  {Binding} command as you can see below:

The ItemsControl ItemSource was bound to the List of strings here, and as such each DataTemplate would be associated with a single string. Hence to get the Text value to be the single string I used  Text="{Binding}" to bind to the Parent. When binding to a list that contained an empty string, this was the result:

XAML binding issue

The last text box where the empty string was supposed to be has instead seemingly been populated by the type of the ViewModel. I believe something strange is happening when the empty string is the parent, and the binding is propagating up one more level to the Parent (which is the ItemViewModel).

The Solution

I found no solutions to this other than creating a separate ViewModel for the strings in my List that contained one Property for the string. I then bound to this and the behavior was as I would expect, as I was no longer ever having to bind to the parent, instead I could explicitly bind to a property. This code is below:

This produced the following output:

Corrected output for the List

Now this with the explicit  Text="{Binding Value}" works as I am no longer having to deal with binding to parents. I have provided a simple example application that highlights this issue that you can download below:

Download Example

Example of XAML issue when binding to List of strings 310.6 KB

Leave a Reply