mvvm - WPF - Data Binding -


i new wpf. far understand, data bound controls automatically update when source data changed. why change ui through data rather manipulating directly? mean, if want change text of label, why choose change bound data rather text property directly?

then might ask why bound data source in first place. seems solution in order instantiate xaml template data coming server. way, don't have write imperative code in code behind initial rendering of view. when want update it, have via code anyway, use data binding.

so question is, why change view model rather changing view itself?

your question why should use mvvm , data binding. asking why not textbox.text="helloworld" rather textbox.text="{binding someviewmodelproperty".

since working in wpf/mvvm last 4 years, can tell answer in short. approach you're saying here best suited small single page application. have single page application 3 textboxes. need textbox values server. place 3 textboxes in view. in code behind ie xaml.cs can write,

textbox1.text = someservercallordbcall.getdata1(); textbox2.text = someservercallordbcall.getdata1(); textbox3.text = someservercallordbcall.getdata1(); 

consider large application. need display 100's of fields in view. need fetch data multiple servers , services. need navigate between views , exchange data between views, services or databases. @ time, called databinding/mvvm approach lot. in separation of concerns. if write these code in code behind(ie xaml.cs), code become cumbersome , code reusability, readability , maintainability poor. if want change field, or test part of application, difficult search line of code in vast code behind. use mvvm. many people can work in single project @ same time. while 1 developer designing view, other developer create view model. makes testing easy too. mvvm enables achieve twoway binding easily. hence when change textbox text, automatically updated in viewmodel property , in turn can used update data in database or service.

hence can follow approach :

<textbox x:name="textbox1" text="{binding viewmodelproperty1, mode=twoway}" /> <textbox x:name="textbox2" text="{binding viewmodelproperty2, mode=twoway}" /> <textbox x:name="textbox3" text="{binding viewmodelproperty3, mode=twoway}" /> 

benefits of mvvm model in nutshell :

  1. maintanability
  2. readability
  3. reusability
  4. better testability
  5. good separation of concern
  6. less code duplication
  7. two way data binding

Comments