Edward Tanguay
Edward Tanguay

Reputation: 193372

Why does XAML element-to-xml binding only partially work?

In the below code, the ListBox gets filled with the names of the colors from the XML file, but those names strangely do not appear in the TextBox.

However, if you bind the textbox to the static "lbColor2", those names do appear.

So what could be different about the names when they come from the XML source which makes them not get passed on?

<StackPanel>
    <StackPanel.Resources>
        <XmlDataProvider x:Key="ExternalColors" Source="App_Data/main.xml" XPath="/colors"/>
    </StackPanel.Resources>
    <TextBlock Text="Colors:"/>
    <ListBox Name="lbColor" IsSynchronizedWithCurrentItem="True" ItemsSource="{Binding Source={StaticResource ExternalColors}, XPath=color/@name}"/>
    <ListBox Name="lbColor2">
        <ListBoxItem>Red</ListBoxItem>
        <ListBoxItem>Orange</ListBoxItem>
        <ListBoxItem>Cyan</ListBoxItem>
    </ListBox>
    <TextBlock Text="You selected color:"/>
    <TextBox
        Text="{Binding ElementName=lbColor, Path=SelectedItem.Content}"
        >
    </TextBox>
</StackPanel>

Here is the XML file:

<?xml version="1.0" encoding="utf-8" ?>
<colors>
  <color name="Pink"/>
  <color name="Cyan"/>
  <color name="LightBlue"/>
  <color name="LightGreen"/>
  <color name="Another One"/>
</colors>

Upvotes: 0

Views: 450

Answers (1)

Kent Boogaart
Kent Boogaart

Reputation: 178760

You've bound the TextBox to SelectedItem.Content, but XmlAttribute does not have a property called Content. Change to this and you'll be fine:

<TextBox Text="{Binding ElementName=lbColor, Path=SelectedItem.Value}"/>

Upvotes: 1

Related Questions