zoukankan      html  css  js  c++  java
  • WPF xml的绑定

    写点一般的小程序,没必要用SQL数据库,xml也能搞定,这个是我自己总结的,若有不足或错误的地方请见谅和提醒。

    WPF里的xml有两种方式

    1. 第一种没有.xml这个文件,而是把数据写到Window.Resources里面,当然这种情况数据是写死的。
    2. 第二种就是能够加载外部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");
            }

    简单的应用就这样

  • 相关阅读:
    C++ 11 Lambda表达式
    Hello word!
    nginx 官方文档翻译
    Http读书笔记1-5章
    ROM、RAM、DRAM、SRAM和FLASH的区别
    优化专题
    Typescript学习
    canvas实现的粒子效果
    【转载】js常用方法和片段
    【转载】图解正向代理、反向代理、透明代理
  • 原文地址:https://www.cnblogs.com/HelloMyWorld/p/2618591.html
Copyright © 2011-2022 走看看