WPF binding to XPath-reachable value of an element property

时光总嘲笑我的痴心妄想 提交于 2019-12-21 05:49:14

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/436333/wpf-binding-to-xpath-reachable-value-of-an-element-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!