WPF,使用 XAML 中的 XPath 和 XmlDataProvider 根据 ComboBox 中选定的值选择节点

2023-12-12

这个问题与我的上一个问题但更具体。假设我有两个组合框,一个填充了产品名称,另一个为空。选择产品后,我希望第二个组合框填充与该产品相关的数据。我有如下 XML:

<Products>
    <Product name="MyProduct1">
        <Components>
            <Component name="MyComponent1"/>
            <Component name="MyComponent2"/>
            ...more Component nodes...
        </Components>
    </Product>
    ...more Product nodes...
</Products>

我希望我能以某种方式设置XPath在组件组合框上,这样它就可以获取所有Components/Component节点从Product节点的@name属性等于产品组合框中当前选定的值。这可能吗?我该怎么做呢?到目前为止,我的 XAML 中包含以下内容:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0"
          Name="cbo_product" VerticalAlignment="Top" Width="120"
          ItemsSource="{Binding Source={StaticResource productsXml}}"
          DisplayMemberPath="@name"/>
<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,151,0,0"
            Name="cbo_component" VerticalAlignment="Top" Width="201"
            DisplayMemberPath="@name">
    <ComboBox.ItemsSource>
        <!-- Currently gets all Component nodes--want it to get only those
             associated with the selected Product -->
        <Binding Source="{StaticResource productsXml}"
                 XPath="Components/Component"/>
    </ComboBox.ItemsSource>
</ComboBox>

Product ComboBox 中充满了产品名称,例如 MyProduct1,因此该部分没问题。这是我需要帮助的依赖组件组合框。


在谷歌搜索 WPF 中的 XPath 表达式的示例后,我发现本文这以一种迂回的方式给了我我的解决方案。他的示例比我的更复杂,因此我不必创建 XML 转换器类。我只需要以下 XAML 作为我的依赖组件组合框:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,151,0,0"
          Name="cbo_component" VerticalAlignment="Top" Width="201"
          DataContext="{Binding ElementName=cbo_product, Path=SelectedItem}"
          ItemsSource="{Binding XPath=Components/Component}"
          DisplayMemberPath="@name"/>

Here, cbo_product is the Name我的产品组合框。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

WPF,使用 XAML 中的 XPath 和 XmlDataProvider 根据 ComboBox 中选定的值选择节点 的相关文章

随机推荐