Skip to main content
 首页 » 编程设计

c#之WPF,XML 数据绑定(bind)到依赖/级联组合框

2024年02月24日19sharpest

我有一个具有以下结构的 XML 文件:

<Products> 
  <Product name="MyProduct1"> 
    <Components> 
      <Component name="MyComponent1"> 
        <SubComponents> 
          <SubComponent name="MySubComponent1"/> 
          <SubComponent name="MySubComponent2"/> 
          ...more SubComponent nodes... 
        </SubComponents> 
      </Component> 
      ...more Component nodes... 
    </Components> 
  </Product> 
  ...more Product nodes... 
</Products> 

我正在尝试创建一个 WPF 应用程序,其中包含一个包含产品名称的 ComboBox。我对 WPF 完全陌生,所以我不知道我是否以正确的方式处理事情。选择产品后,第二个 ComboBox 应填充该产品的所有组件。 And when a Component is chosen, a third ComboBox should be populated with all the SubComponents for that Component.

除了在独立组合框触发的事件处理程序中填充依赖组合框外,我不知道如何在组合框之间建立依赖关系。这似乎暗示我需要能够在 C# 中读取 XML,所以我有 [Serializable] Products、Product、Component 和 SubComponent 类。但是,我试图在我的 XAML 中进行 XML 数据绑定(bind):

<Window.Resources> 
    <XmlDataProvider Source="Products.xml" 
                     XPath="Products/Product" 
                     x:Key="productsXml"/> 
</Window.Resources> 

我目前在我的第一个 ComboBox 中没有看到产品名称列表,其 XAML 如下:

<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0" 
          Name="cbo_product" VerticalAlignment="Top" Width="120" 
          ItemsSource="{Binding Source=productsXml, XPath=@name}" 
          SelectionChanged="product_SelectionChanged"/> 

Products XML 应该是只读的——用户将无法从应用更改 XML 中的任何值。我只想读取 XML 数据并将其显示在应用程序中。

我有几个问题:

  1. 我做的正确吗?有一个独立的 XML 文件,我的 WPF 应用程序从中读取,有 [Serializable] 类表示 XML 文件中的节点,以便从 C# 中的这些节点中提取数据,使用事件处理程序来编码依赖项在组合框等之间。
  2. 为什么我的产品名称(例如 MyProduct1)没有显示在我的 ComboBox 中?目前它只是显示为空。
  3. 用 [Serializable] 类来表示我的 XML 节点似乎是多余的/不必要的,因为 XAML 已经有了 XmlDataProvider/XPath 东西。是这样吗?

编辑:

将我的 ComboBox XAML 更新为以下内容,现在我在 ComboBox 中看到了我的产品名称列表,感谢 decyclone's answer :

<ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0" 
          Name="cbo_product" VerticalAlignment="Top" Width="120" 
          ItemsSource="{Binding Source={StaticResource productsXml}}" 
          DisplayMemberPath="@name" 
          SelectionChanged="product_SelectionChanged"/> 

请您参考如下方法:

ItemsSource 属性应设置为要显示在列表中的项目集合,在您的情况下为 XmlDataProvider。使用 StaticResource 来定位它,因为它被定义为资源。 DisplayMemberPath 属性应该用于选择应该使用什么属性来显示组合框中的文本。

关于您的第一个(和第三个)问题,我个人更喜欢创建类而不是使用原始 XML。它给了我一些好处,比如

  • 添加包装属性。例如,FullName = FirstName + ""+ LastName 属性。

  • 每次我想要访问值(始终是字符串)时,我都不必检查空值和类型安全性。

  • 我可以添加自己的行为作为方法,这对于完成一些小任务非常有用。

  • 控制序列化方法并使用属性在其中注入(inject)自定义逻辑。

关键是,值得吗?你真的在乎这些好处吗?这就像在 DataReader 和 DataSet 之间进行选择一样。为了只读和只显示目的,使用原始 XML,如果您要经常使用它,请使用类。