WPF, XML databinding into dependent/cascading ComboBoxes

前端 未结 2 988
北荒
北荒 2020-12-22 04:28

I have an XML file with the following structure:


  
    
      

        
相关标签:
2条回答
  • 2020-12-22 05:04

    The ItemsSource property should be set to a collection of items that are to be displayed in the list which is XmlDataProvider in your case. User StaticResource to locate it since it is defined as a resource. The DisplayMemberPath property should be used to select what property should be used to display text in combobox.

    Regarding your 1st (& 3ed) question, I personally like create classes than using raw XML. It gives me few benefits like

    • Adding wrapper properties. For example, FullName = FirstName + " " + LastName property.

    • I dont have to check for empty values and type safety everytime I want to access the values (which are always strings).

    • I can add my own behaviors as methods which can be really useful for doing little tasks.

    • Control the serialization method and inject custom logic in it using attributes.

    The point is, is it worth it? Do you really care for these benefits? It's just like choosing between DataReader and DataSet. For readonly and displayonly purpose, use raw XML and if you are going to play with it a lot, use classes.

    0 讨论(0)
  • 2020-12-22 05:14

    Okay, since I found an answer to my more specific question, I think I know the answer to this question, too. I don't need [Serializable] classes for the different nodes in my XML, because I can just use XAML and XPath to create cascading/dependent ComboBoxes:

    <!-- Independent -->
    <ComboBox Height="23" HorizontalAlignment="Left" Margin="138,116,0,0"
              Name="cbo_product" VerticalAlignment="Top" Width="120"
              ItemsSource="{Binding Source={StaticResource productsXml}}"
              DisplayMemberPath="@name"/>
    
    <!-- Dependent -->
    <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"/>
    
    0 讨论(0)
提交回复
热议问题