OneTime绑定:单次绑定,绑定后数据改变界面不会发生改变 

 

OneWay绑定:单向绑定,这个是绑定的默认值,当我们改变数据源的值时,界面上面的值会发生改变,但当我们改名界面上面的值时,数据源数据不会发生变化(Eval)

 

TwoWay绑定:双向绑定,任意一方数据改变都会触发数据源或界面上面的值(BIND)

 

slider 进度滚动条

        <TextBox Text="{Binding Value,Mode=TwoWay,ElementName=s1}"/>

        <Slider Maximum="100" Minimum="0" x:Name="s1" Width="299"/>


这个是最基本的一个绑定列子,下面我们看一看把一个对象的属性绑定到控件上面去

首先定义一个类Person

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GridExp
{
    public class Person : INotifyPropertyChanged
    {
        private string _name;
        private int _age;
        public int Id { get; set; }
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));
                }
            }
        }
        public int Age
        {
            get
            {
                return _age;
            }
            set
            {
                _age = value;
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
    }

}

INotifyPropertyChanged接口规定了当属性更改时,向界面发送通知,这个事件时相对于Binding来说的,如果没有Binding,则不起任何作用

然后在前台定义3个控件

    <TextBox Text="{Binding Name}" x:Name="bx" Width="200" Height="50"/><!--把控件的Text属性绑定到数据源的Name属性上-->
        <Button Content="读出Person的值" Click="Button_Click_1"></Button>
        <Button Content="修改Person的值" Margin="400,400,0,0" Click="Button_Click_2"></Button>

后台数据绑定

 private Person p = new Person() { Name = "XXX", Age = 21 };

        public GroupedItemsPage()
        {
            this.InitializeComponent();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            bx.DataContext = p;
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            MessageDialog dlg = new MessageDialog(p.Name);
            dlg.ShowAsync();
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            p.Name = DateTime.Now.Millisecond.ToString();
        }

 这里需要提一下,就是内层控件会继承外层控件的数据源(数据上下文),也就是说,上面数据绑定的代码如果写成

protected override void OnNavigatedTo(NavigationEventArgs e)
        {

            this.DataContext = p;
        }

也是可以的

 

posted on 2012-12-03 14:16  振宇爸爸  阅读(142)  评论(0编辑  收藏  举报