0

To start, understand that I'm dealing with a dynamic interface that is generated at run-time from XML. I have written XAML that switches on various elements and attributes to create the appropriate controls and labels, in order to display the data contained in the augmented XML file.

Sample XML fragment:

   <floop Format="combo" Choices="apple;banana;cherry" Value="cherry"/>

Format and value works already. I'm looking for a way to make Choices work. (Yes this is unconventional for XML, but it serves the purpose for now.)

Here's a proposed XAML fragment:

 <ComboBox Style="{StaticResource ComboButtonStyle}"  
         Width="200"
         ItemsSource="{Binding XPath=@Choices}" IsEditable="True"
         />

The thing is, @Choices is a single string, so I'm proposing to parse the string to produce the type of data ItemsSource wants.

How do I get there from here?

Alan Baljeu
  • 2,383
  • 4
  • 25
  • 40

1 Answers1

1

You want to use a converter on the Binding to take it from a string to a list. This answer does the opposite.

I haven't tested this code but it should get you where you want to go.

<ComboBox Style="{StaticResource ComboButtonStyle}" Width="200" ItemsSource="{Binding XPath=@Choices, Converter={StaticResource StringToListConverter}}" IsEditable="True" />

[ValueConversion(typeof(string), typeof(List<string>))]
public class StringToListConverter : IValueConverter
{

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (targetType != typeof(List<string>))
            throw new InvalidOperationException("The target must be a List<string>");

        return new List<string>(((string)value).Split(';'));
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
Community
  • 1
  • 1
techvice
  • 1,315
  • 1
  • 12
  • 24
  • To fix, I added to Resounces, and changed the Converter reference to Converter={StaticResource stringToListConverter} – Alan Baljeu Feb 20 '15 at 16:39
  • Okay next problem: Convert is receiving an XmlDataCollection and a System.Collections.IEnumerable, not string and List. I can switch the types on the latter, but what's up with this XmlDataCollection? – Alan Baljeu Feb 20 '15 at 16:54
  • @AlanBaljeu Looks like it will use that as opposed to just a string. I wouldn't worry about it. Try changing `string` to `XmlDataCollection` and see if you can get it to work. You will have to tweak the code a bit. As for the converter, I knew you would have to make additional changes but how you did it is appropriate. – techvice Feb 20 '15 at 16:59
  • 1
    For future reference what I eventually did: Remove XPath=@choices, and then receive an XML element in the converter. From there I can write C# to access the attribute from the XmlElement. – Alan Baljeu Feb 20 '15 at 21:32