WPF学习笔记12. Binding (5)
2010-10-11 16:35:20 来源:本站整理Personals.xml
<?xml version="1.0" encoding="utf-8" ?> <Personals xmlns=""> <Personal Name="Tom" Age="15" Sex="Male" /> <Personal Name="Mary" Age="11" Sex="Female" /> <Personal Name="Jack" Age="12" Sex="Male" /> </Personals>
在 Source 属性中指定 XML Uri。
当然,我们也可以在程序代码中通过 XmlDocument 来控制 XML 数据源。
Window1.xaml
<Window x:Class="Learn.WPF.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1">
<Window.Resources>
<XmlDataProvider x:Key="personals" />
</Window.Resources>
<Grid>
<StackPanel DataContext="{StaticResource personals}">
<ListBox x:Name="listbox1" ItemsSource="{Binding XPath=*}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding XPath=@Name}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding XPath=@Age}" />
<TextBlock>,</TextBlock>
<TextBlock Text="{Binding XPath=@Sex}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</Grid>
</Window>
Window1.xaml.cs
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
var xml = new XmlDocument();
xml.Load("Personals.xml");
var provider = this.FindResource("personals") as XmlDataProvider;
provider.Document = xml;
provider.XPath = "Personals";
}
}
逻辑代码只需修改 XmlDocument 即可自动同步显示到界面上。
protected void ButtonClick(object sender, RoutedEventArgs e)
{
var provider = this.FindResource("personals") as XmlDataProvider;
var xml = provider.Document;
var mary = xml.SelectSingleNode("Personals/Personal[@Name=\"Mary\"]") as XmlElement;
var age = Convert.ToInt32(mary.Attributes["Age"].Value);
mary.Attributes["Age"].Value = (++age).ToString();
}
如果设置了 Source 属性,则放弃所有内联 XML 数据;如果设置了 Document 属性,则清除 Source 属性并放弃所有内联 XML 数据。
设置以下属性将隐式导致此 XmlDataProvider 对象刷新:Source、Document、XmlNamespaceManager 和 XPath。
在更改多个导致刷新的属性时,建议使用 DeferRefresh。
更多精彩
赞助商链接