您的位置:首页 > 产品设计 > UI/UE

Tips: Save some typing when binding values to UI in WPF/Silverlight

2013-06-11 19:08 381 查看
Asweallknow,InWPForSilverlightapplication,ifwewanttoupdatethevalueintheUIwhentheunderlyingdatahaschanged,theclassneedtoimplementthe"INotifyPropertyChanged”interface,whichcontainsonedelegate"PropertyChangedEventHandler”.

Socreateanewmethod,andtaketheincomingparameterandpassittotheeventargument,makesurecallthemethodeverytimewhenthepropertyhaschanged.justlikethestandardtextbooksaid.

Howaboutcreatethatmethodthisway:

ImportSystem.Runtime.CompilerServicesnamespace.

publiceventPropertyChangedEventHandlerPropertyChanged;


privatevoidOnPropertyChanged([CallerMemberName]stringcaller="")

{

if(PropertyChanged!=null)

{

PropertyChanged(this,newPropertyChangedEventArgs(caller));

}

}


With[CallerMemberName]attribute,youdon’thavetoexplicitpassinthepropertynameanymore,justcallitinthesetpart,Frameworkwilltakecareoftherest.likethis:

privatestring_foo;

publicstringFoo

{

get

{

return_foo

}

set

{

_foo=value;

OnPropertyChanged();

}

}


It’snotsomebigorfancythings,butmaybeyourkeyboardwilllivelonger.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: