如何将TextBlock与XML绑定?

时间:2013-07-12 15:10:40

标签: wpf xml xaml xaml-binding

我想制作一个改变语言系统,改变XML文件。

我有一个XML文件,这个结构是这样的:

<List>
    <File>Arquivo</File>
    <Edit>Editar</Edit>
    <View>Visual</View>
</List>

在我的WPF

<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="File" VerticalAlignment="Top" Text="File">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="Edit" VerticalAlignment="Top" Text="Edit">
<TextBlock Height="23" HorizontalAlignment="Left" Margin="12,12,0,0" Name="View" VerticalAlignment="Top" Text="View">

那么,如何将此TextBlock's文本与XML文件值绑定?

1 个答案:

答案 0 :(得分:2)

首先,您需要创建XmlDataProvider,如下所示:

<Window.Resources>
  <XmlDataProvider x:Key="InventoryData">
      <x:XData>
          <List xmlns="">
              <File>Arquivo</File>
              <Edit>Editar</Edit>
              <View>Visual</View>
          </List>
      </x:XData>
  </XmlDataProvider>
</Window.Resources>

您还可以通过指定XmlDataProvider.Source从外部XML文件加载它。当您拥有源代码时,可以通过将Binding.Source指定为InventoryData并将Binding.XPath指定给您感兴趣的节点来绑定它,如下所示:

<StackPanel>
  <TextBlock Text="{Binding Source={StaticResource InventoryData}, XPath=List/File}"/>
  <TextBlock Text="{Binding Source={StaticResource InventoryData}, XPath=List/Edit}"/>
  <TextBlock Text="{Binding Source={StaticResource InventoryData}, XPath=List/View}"/>
</StackPanel>