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.
With[CallerMemberName]attribute,youdon’thavetoexplicitpassinthepropertynameanymore,justcallitinthesetpart,Frameworkwilltakecareoftherest.likethis:
It’snotsomebigorfancythings,butmaybeyourkeyboardwilllivelonger.
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.
相关文章推荐
- Silverlight Tips[4]: How to convert bytes to image in WPF
- Binding to Resources in Silverlight/WPF
- Binding UI Events from View to commands in ViewModel in Silverlight 4(转)
- Some Tips When handle Dataset in VS 2005
- Binding and styling text to a RichTextBox in WPF
- add a splash to load system is easy:1:add spashWnd,then call it in instance ,when some work ok,close it.
- UI Automation in WPF/Silverlight
- Error message when you try to save a table in SQL Server 2008: "Saving changes is not permitted"
- Element to Element Binding in Silverlight
- Silverlight Tips[1]: How to save file without savefiledialog
- Authentication Failed when trying to use Save As in the IE Browser
- Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01
- Save results to different files when executing multi SQL statements in DB Query Analyzer 7.01
- Binding and styling text to a RichTextBox in WPF
- UI Automation in WPF/Silverlight
- Binding to a dictionary in Silverlight with INotifyPropertyChanged
- Binding Events to Methods in the Silverlight MVVM View Models
- Use View.isInEditMode() in your custom views to skip code when shown in Eclipse
- How to save data in ASCII format in ADS for use in MATLAB
- *****How to scroll in the grid when editing data in a cell