开始
前两篇,太简单了。这次我们来一个有难度,但是很好玩的------》数据绑定
什么是数据绑定?
举个生动例子
.
我是一个爱吃爱睡叫的人,怎么睡都喜欢,什么都爱吃
最近呢,出现了一个 A 某 ,他多我很关心
我睡觉落枕了 他就告诉我怎么睡觉才不会落枕
我吃东西闹肚子了 他就告诉我应该吃什么,不应该吃什么
结束:我们可以发现,我出现对应的症状,A某就会出现对应的关心
这是一一对应的,就好像 A 某装了监视器一样
我发生某个行为,触发了 A 某的一个特定的行为
这种呢,就是单向绑定
那么什么是双向绑定?
通俗的讲 我和 A 某 ,发生了互相关心,互相装监控器,并且触发行为
好了,我们上马
上马
public class BindTest : Test
{
class Binder_A : BindableObject
{
private string _value;
public string value { get { return GetProperty ( ref _value) ; } set { SetProperty ( ref _value, value ) ; } }
}
class Binder_B : BindableObject
{
private string _value;
public string value { get { return GetProperty ( ref _value) ; } set { SetProperty ( ref _value, value ) ; } }
}
private void Bind_Test ( )
{
Log. L ( "init BindableObject Test" ) ;
BindableObjectHandler binder = new BindableObjectHandler ( ) ;
Binder_A a = new Binder_A ( ) ;
Binder_B b = new Binder_B ( ) ;
Log. L ( $"a.value = { a. value } \tb.value= { b. value } " ) ;
Log. L ( "bind" ) ;
binder. BindProperty ( ( value ) => { a. value = value ; } , ( ) => { return a. value ; } )
. BindProperty ( ( value ) => { b. value = value ; } , ( ) => { return b. value ; } ) ;
Log. L ( $"a.value = { a. value } \tb.value= { b. value } " ) ;
Log. L ( "change value to a" ) ;
a. value = "a" ;
Log. L ( $"a.value = { a. value } \tb.value= { b. value } " ) ;
Log. L ( "change value to b" ) ;
b. value = "b" ;
Log. L ( $"a.value = { a. value } \tb.value= { b. value } " ) ;
}
protected override void Start ( )
{
Log. L ( "Single direction" ) ;
Observable_Test ( ) ;
Log. L ( "---------------------------------------" ) ;
Log. L ( "Double direction" ) ;
Bind_Test ( ) ;
}
private void Observable_Test ( )
{
Log. L ( "init ObservableObject Test" ) ;
ObservableObjectHandler binder = new ObservableObjectHandler ( ) ;
Observable_A a = new Observable_A ( ) ;
Log. L ( $"a.value = { a. value } " ) ;
Log. L ( "bind" ) ;
binder. BindProperty (
( value ) => {
a. value = value ;
Log. L ( $"listen change a.value to { value } " ) ;
} ,
( ) => { return a. value ; }
) ;
Log. L ( $"a.value = { a. value } " ) ;
Log. L ( "change value to a" ) ;
a. value = "a" ;
Log. L ( $"a.value = { a. value } " ) ;
Log. L ( "change value to b" ) ;
a. value = "b" ;
Log. L ( $"a.value = { a. value } " ) ;
}
class Observable_A : ObservableObject
{
private string _value;
public string value { get { return GetProperty ( ref _value) ; } set { SetProperty ( ref _value, value ) ; } }
}
protected override void Stop ( )
{
}
protected override void Update ( )
{
}
}
来看看输出
结束
看完代码和结果,是不是很有意思的?
那怎么实现的呢?
后续文章讲解,hey hey hey
简单透露以下 ---》委托