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

本文介绍了DatabindingMode中的三种模式:OneTime、OneWay和TwoWay,并详细解释了它们的功能区别。此外还提供了实现这些绑定模式的具体代码示例。


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


Databinding Mode
OneTime目标控件的属性只更新一次,以后的更新会被忽略
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" />



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值