寫點一般的小程序,沒必要用SQL數據庫,xml也能搞定,這個是我自己總結的,若有不足或錯誤的地方請見諒和提醒。
WPF里的xml有兩種方式
- 第一種沒有.xml這個文件,而是把數據寫到Window.Resources里面,當然這種情況數據是寫死的。
- 第二種就是能夠加載外部xml文件的。
細說第二種,首先是將xml文件作為資源載入
<XmlDataProvider x:Key="StylePlayer" Source="F:\WPF設計\綁定XML\綁定XML\StylePlyer.xml" XPath="StylePlayer/Music"></XmlDataProvider>
注意的是XPath這個家伙,我的xml文件是這樣的,這里XPath要寫的是xml的根,並且不能寫成 XPath="StylePlayer",必須寫成XPath="StylePlayer/Music",我也不知道為什么這樣,懂的大神希望告之,感激不盡~~
<?xml version="1.0" encoding="utf-8"?> <StylePlayer> <Music id="001"> <Singer>孫燕姿</Singer> </Music> <Music id="002"> <Singer>梁靜茹</Singer> </Music> </StylePlayer>
下面就是綁定到控件了,唯一需要注意的就是,如果是屬性的話,前面要加@
<StackPanel DataContext="{StaticResource StylePlayer}"> <Label Width="200" Height="50" Content="{Binding XPath=@id}"></Label> <ListBox Width="210" Height="150" ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <Label Width="200" Height="50" Content="{Binding XPath=Singer}"></Label> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <TextBox Width="200" Height="50" Text="{Binding XPath=Singer,Mode=TwoWay}"></TextBox> <Button Width="200" Height="50" Click="Button_Click"></Button> </StackPanel>
保存也很簡單
private void Button_Click(object sender, RoutedEventArgs e) { XmlDataProvider xml = (XmlDataProvider)this.FindResource("StylePlayer"); xml.Document.Save(@"F:\WPF設計\綁定XML\綁定XML\StylePlyer.xml"); }
簡單的應用就這樣