Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - How to parse an XML attribute for a WPF binding

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...