WPF 数据绑定

来源:互联网 发布:php异步请求 编辑:程序博客网 时间:2024/06/06 03:47

WPF中的数据绑定非常的灵活,使用起来也是十分的简单,这里我不扯什么理论知识了发个链接 想仔细研究的同学 可以自己去慢慢看

MSDN http://msdn.microsoft.com/zh-cn/library/ms752347(v=vs.100).aspx

本文主要是针对那些个想迅速了解数据绑定 直接上手的同学所写,废话不多说 上代码


<Window x:Class="DataBindingDemo.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="MainWindow" Height="700" Width="525">    <StackPanel>        <StackPanel Orientation="Horizontal" Margin="10" >            <TextBlock  Text="Binding DependencyObject Property:" FontWeight="Bold"/>            <TextBox x:Name="DP_Property" Text="test text" />            <TextBlock Text="{Binding ElementName=DP_Property,Path=Text}" ToolTip="{Binding RelativeSource={RelativeSource self},Path=Text}"/>        </StackPanel>        <StackPanel Orientation="Horizontal" Margin="10" >            <TextBlock Text="Binding CLR Object Property:" FontWeight="Bold"/>            <TextBlock x:Name="TBSimpaleCLR" Text="{Binding ShowText}"/>            <Button Width="70" Height="30" Content="auto update text" Click="AutoUpdateCLRProperty_Click"/>        </StackPanel>        <StackPanel  Margin="10" >            <TextBlock Text="Binding CLR Object List:" FontWeight="Bold"/>            <ItemsControl x:Name="IC_CLRList">                <ItemsControl.ItemTemplate>                    <DataTemplate>                        <TextBlock Text="{Binding ShowText}"/>                    </DataTemplate>                </ItemsControl.ItemTemplate>            </ItemsControl>        </StackPanel>        <StackPanel  Margin="10" >            <TextBlock Text="Binding CLR Object ObservableCollection:" FontWeight="Bold"/>            <ItemsControl x:Name="IC_CLRListObservableCollection">                <ItemsControl.ItemTemplate>                    <DataTemplate>                        <TextBlock Text="{Binding ShowText}"/>                    </DataTemplate>                </ItemsControl.ItemTemplate>            </ItemsControl>            <Button Content="Change data ui update" HorizontalAlignment="Left"                    Width="120" Height="30" Click="ObservableCollectChange_Click"/>        </StackPanel>        <StackPanel Margin="10" >            <TextBlock Text="Binding Linq Query" FontWeight="Bold"/>            <ItemsControl x:Name="IC_LinqCLR">                <ItemsControl.ItemTemplate>                    <DataTemplate>                        <TextBlock Text="{Binding ShowText}"/>                    </DataTemplate>                </ItemsControl.ItemTemplate>            </ItemsControl>        </StackPanel>                        <StackPanel Margin="10" >            <TextBlock Text="Binding XElement" FontWeight="Bold"/>            <ItemsControl x:Name="IC_Linq2XML">                <ItemsControl.ItemTemplate>                    <DataTemplate>                        <TextBlock Text="{Binding Path=Attribute[name].Value}"/>                    </DataTemplate>                </ItemsControl.ItemTemplate>            </ItemsControl>        </StackPanel>            </StackPanel></Window>//code behindusing System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows;using System.Windows.Controls;using System.Windows.Data;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Imaging;using System.Windows.Navigation;using System.Windows.Shapes;using System.ComponentModel;using System.Collections.ObjectModel;using System.Xml.Linq;namespace DataBindingDemo{    /// <summary>    /// Interaction logic for MainWindow.xaml    /// </summary>    public partial class MainWindow : Window    {        TestObject _clr;        List<TestObject> _list = new List<TestObject>();        ObservableCollection<TestObject> _observablelist = new ObservableCollection<TestObject>();        XElement _linq2xml;        public MainWindow()        {            InitializeComponent();            InitData();            //linq query find showtxt is not 1 in _list             var query = from i in this._list                        where i.ShowText != "1"                        select i;            //binding datacontext in textblock            this.TBSimpaleCLR.DataContext =this._clr ;            //binding itemssource to clr list            this.IC_CLRList.ItemsSource = this._list;            //binding itemssource to linq query            this.IC_LinqCLR.ItemsSource = query;            //binding itemssource to xelement            this.IC_Linq2XML.ItemsSource = _linq2xml.Elements("a");            //binding itemssource to observablecollection            this.IC_CLRListObservableCollection.ItemsSource = this._observablelist;        }        void InitData()        {            this._clr = new TestObject() { ShowText = "test clr object property" };            _linq2xml = XElement.Parse("<list><a name='123' /><a name='456' /><a name='789' /></list>");            this._list.Add(new TestObject() { ShowText = "1" });            this._list.Add(new TestObject() { ShowText = "2" });            this._list.Add(new TestObject() { ShowText = "3" });            this._observablelist.Add(new TestObject() { ShowText = "1" });            this._observablelist.Add(new TestObject() { ShowText = "2" });            this._observablelist.Add(new TestObject() { ShowText = "3" });            this._observablelist.Add(new TestObject() { ShowText = "4" });        }        private void AutoUpdateCLRProperty_Click(object sender, RoutedEventArgs e)        {            this._clr.ShowText = "updated text";        }        private void ObservableCollectChange_Click(object sender, RoutedEventArgs e)        {            this._observablelist.RemoveAt(0);        }    }    public class TestObject : INotifyPropertyChanged    {        private string _showText;        public string ShowText { get { return this._showText; } set { this._showText = value; OnPropertyChanged("ShowText"); } }        public event PropertyChangedEventHandler PropertyChanged;        void OnPropertyChanged(string name)        {            if (PropertyChanged != null)                this.PropertyChanged(this, new PropertyChangedEventArgs(name));        }    }}


以上例子里面包含了基本上所有的数据绑定

包括依赖属性的绑定、clr属性绑定、clr对象List绑定、CLR对象的observableCollection的绑定、XML绑定、Linq Query的绑定下面具体说明


1.依赖属性的绑定

从例子里可以看出 我们可以通过Text="{Binding ElementName=DP_Property,Path=Text}" 我们可以将一个textblock的text字段与textbox的text字段绑定 

        ElementName是要绑定的数据源的name即textbox的名字

        path是指绑定的属性名称这里我们绑定Text 

这样 我们在修改textbox的内容的时候 textblock的内容也会自动改变

同理ToolTip="{Binding RelativeSource={RelativeSource self},Path=Text}" 将tooltip绑定了自身的text自动


2.CLR对象属性的绑定

在后台代码中this.TBSimpaleCLR.DataContext =this._clr ;就是将clr对象赋值给前台的空间的datacontext

这样前台的控件就有了数据对象了 在xaml中使用绑定<TextBlock x:Name="TBSimpaleCLR" Text="{Binding ShowText}"/>

就可以将控件的text属性绑定到clr对象的ShowText字段上了

这里要注意下 如果clr对象实现了INotifyPropertyChanged接口的话   只需要修改clr对象的ShowText字段 前台的ui也会自动更新

具体的请看代码中的TestObjectde 定义


3.在对一些列表类控件进行数据绑定 显示数据列表的时候 可以选择List 和ObservableCollection两种列表对象

不同之处在于使用List绑定控件的itemssource属性时候 如果更改了list内容 ui不会更新

而使用observablecollection对象绑定到itemssource的时候 如果列表更改了 ui也会随之更改

具体的可以看代码中的实例


4.linq query的绑定 实际上就是和3类似 没有什么特殊的地方 这里 不在赘述


5.XElement的绑定

只有一点需要大家注意的地方 那就是xaml中绑定的format 

<TextBlock Text="{Binding Path=Attribute[name].Value}"/> 其中Attribute[name].Value 指的是绑定xml中名称为name的属性值

当然你也可以绑定xml中的值<TextBlock Text="{Binding Path=Value}"/> 这样就可以直接绑定xml中的节点值

<list>

<node name='123'>node1</node>

<node name='456'>node2</node>

</list>

如果绑定了list里面的node节点

那么<TextBlock Text="{Binding Path=Attribute[name].Value}"/>现实的就是123 456

<TextBlock Text="{Binding Path=Value}"/>  显示的就是node1 node2


当然 你也可以绑定ado的对象实际上我是不推荐这样直接绑定数据的 具体的例子也就不贴出来了 大家可以自己去试试

本文仅仅是针对绑定的使用做了简单的介绍 其中还有数据转换 数据验证 多值绑定等等很多内容 这里就不一一介绍了,也许以后有空了再写吧。