开发者

WPF binding XML data to GUI items

开发者 https://www.devze.com 2023-01-13 13:22 出处:网络
I\'m new to WPF and don\'t yet have a solid grasp of how things should be done... I have an xml file that stores config data and I want the data that is in this xml file to be displayed on the gui f

I'm new to WPF and don't yet have a solid grasp of how things should be done...

I have an xml file that stores config data and I want the data that is in this xml file to be displayed on the gui front end.

I'm currently using an XmlDataProvider that reads in a set of data

The data is roughly like:

<Items>
  <Item name="item01">
    <Position x="0", y="0"/>
  </Item>
  <Item name="item02">
    <Position x="0", y="0"/>
  </Item>
  <Item name="item03">
    <Position x="0", y="0"/>
  </Item>
</Items>

The XmlDataProvider is declared as a resource as follows

<Window.Resources>
    <XmlDataProvider x:Key="SiteConfigFile"  XPath="SiteConfig" >
    </XmlDataProvider>
</Window.Resources>

I then enable a combobox to show each item in the Xml file via a drop down menu using:

<ComboBox Name="ButtonMapping" ItemsSource="{Binding Source={StaticResource SiteConfigFile}, XPath=Items/Item}" DisplayMemberPath="@name" SelectedIndex="0">

This all works fine.

The problem I want to solve now is... depending on which item from the combo box is selected, the corresponding Position element with its 2 attributes need to be shown in atextbox on the g开发者_Go百科ui... do i i need to generate dynamic XPath, that seems a bit messy... what is the best way to do this, I'm out of ideas :(


How about wrapping the TextBox within a couple of panels? See example below. I used an outer panel (Border) whose DataContext is bound to the ComboBox.SelectedItem property. Then, another inner panel (StackPanel) is bound to the element in the XML. Finally within this inner panel, I placed the TextBox control whose Text is bound to @x and @y.

<Border DataContext="{Binding ElementName=ButtonMapping, Path=SelectedItem}">
    <StackPanel DataContext="{Binding XPath=Position}">
        <TextBlock Text="x:"/>
        <TextBox Text="{Binding XPath=@x}"/>
        <TextBlock Text="y:"/>
        <TextBox Text="{Binding XPath=@y}"/>
    </StackPanel>
</Border>

Note though that I used two TextBoxes to display the x and y attributes. If you want to use just one, you'll have to use an IValueConverter to correctly "format" the string you want to show.

0

精彩评论

暂无评论...
验证码 换一张
取 消