Search code examples
xmlwpfxamlcomboboxdefault

Merging text and XML data in combobox items in WPF


I have a ComboBox in WPF that gets data from XML as shown below.

<?xml version="1.0"?>
<Root>
  <Book>
    <Name>Title1</Name>
    <Name>Title2</Name>
    <Name>Title3</Name>
  </Book>
</Root>

<ComboBox x:Name="cb_Book" ItemsSource="{Binding Source={StaticResource XmlData}, XPath=./Book/Name}"/>

I would like to merge a static default text along with items retrieved from XML. I had tried few approaches like CompositeCollection shown here but was unsuccessful. Is there a best way to do this (preferably all in XAML)?

At the end ComboBoxItems should look like this:

Title1      #from XML
Title2      #from XML
Title3      #from XML
MoreTitle   #Static Default text

Solution

  • CompositeCollection and XMLDataProvider is a way to go.

    <StackPanel xmlns:system="clr-namespace:System;assembly=mscorlib">
        <StackPanel.Resources>
            <XmlDataProvider x:Key="XmlData" XPath="./Root/Book/Name">
                <x:XData>
                    <Root xmlns="">
                        <Book>
                            <Name>Title1</Name>
                            <Name>Title2</Name>
                            <Name>Title3</Name>
                        </Book>
                    </Root>
                </x:XData>
            </XmlDataProvider>
            <CompositeCollection x:Key="CompositeCollection">
                <CollectionContainer Collection="{Binding Source={StaticResource XmlData}}"/>
                <system:String>MoreTitle</system:String>
                <system:String>SomeMoreTitle</system:String>
            </CompositeCollection>
        </StackPanel.Resources>
        <ComboBox ItemsSource="{Binding Source={StaticResource CompositeCollection}}"/>
    </StackPanel>