views:

1301

answers:

1

I'd like to bind to a value reachable only with XPath from the property of an element.

The element is a ComboBox populated from some XML, and its property is SelectedItem. SelectedItem points to an XML element, and I'd like to bind to a child element's value within that, which can be reached with an XPath.

The XAML looks like this, so far:

      <StackPanel Orientation="Vertical" Margin="10,10">
        <StackPanel Orientation="Horizontal">
          <Label>Partner</Label>
          <ComboBox Name="Partner" Margin="10,0" 
                    ItemsSource="{Binding XPath=/Root/Tables/Partners/row}" 
                    ItemTemplate="{StaticResource Partner}"/>
        </StackPanel>
        <Button Margin="25,15" Name="Submit" Width="100" Height="30" IsDefault="True"
                CommandParameter="{Binding ElementName=Partner, Path=SelectedItem}">
                Okay
        </Button>
      </StackPanel>

The source XML looks like this:

<Root>
  <Tables>
    <Partners>
      <row>
        <PartnerID>1</PartnerID>
        <Name>FooBar.Com</Name>
      </row>
      <row>
      .
      .
      .
      </row>
    </Partners>
  </Tables>
</Root>

My problem is that the Button's CommandParameter is binding to an XmlElement with too much information in it. I'd like to have CommandParameter refer to a child element, kind of like if I could specify an extra drill-down with "XPath=PartnerID" to return the integer value that I'm really interested in.

+2  A: 

Ended up figuring it out myself. The solution was to set the DataContext of the button to the combobox's SelectedItem, then set the CommandParameter to an XPath binding, like this:

<Button DataContext="{Binding ElementName=Partner, Path=SelectedItem}" 
        Margin="25,15" Name="Submit" Width="100" Height="30" IsDefault="True"
        CommandParameter="{Binding XPath=PartnerID/text()}">Okay</Button>
C. Lawrence Wenham
+1 Your answer is exactly what I was looking for. Cheers!
Andreas Grech