Silverlight 之数据绑定(简单例子)

来源:互联网 发布:浙江建造师网络教育 编辑:程序博客网 时间:2024/05/06 21:11


首先我们先明确Databinding Mode的3种模式:


Databinding ModeOneTime目标控件的属性只更新一次,以后的更新会被忽略OneWay数据对象的值会同步到目标控件的属性,但是目标控件的属性改变不会被同步到数据对象中TwoWay目标控件的属性和数据对象的值相互同步

其中,用于OneWay和TwoWay绑定的对象都必须实现“INotifyPropertyChanged”接口

实现范例:

    public class TestClass : INotifyPropertyChanged    {        public event PropertyChangedEventHandler PropertyChanged;        private int _id;        public int Id        {            get            {                return _id;            }            set            {                _id = value;                _name = "Name" + value;                if (PropertyChanged != null)                {                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));                }            }        }        private string _name="Text Box";        public string Name        {            get            {                return _name;            }            set            {                _name = value;            }        }    }

XAML绑定范例:

首先需要引入绑定对象的命名空间:

xmlns:local="clr-namespace:TestPhoneApp"

定义静态资源:

<phone:PhoneApplicationPage.Resources>        <local:TestClass x:Key="testclass"/>    </phone:PhoneApplicationPage.Resources>

控件绑定:

<TextBox Height="72" HorizontalAlignment="Left" Margin="0,186,0,0" Name="textBox2" Text="{Binding Path=Id, Mode=OneTime, Source={StaticResource testclass}}" VerticalAlignment="Top" Width="460" />            <TextBox Height="72" HorizontalAlignment="Left" Margin="0,287,0,0" Name="textBox3" Text="{Binding Path=Name, Mode=OneWay, Source={StaticResource testclass}}" VerticalAlignment="Top" Width="460" />



原创粉丝点击