c# - Why keep code behind 'clean' and do everything in XAML? -
what benefit of keeping code behind 'clean'?
many times come across posts here trying equivalent in xaml instead of code behind. reason being want keep code behind 'clean'. correct me if wrong, not case that:
initializecomponent();
has run , .g.i.cs file in contains bunch of code though may hidden.is purely psychological? suspect developers come web background , markup opposed code.
edit: don't propose code behind instead of xaml - use both - prefer binding in xaml - against making every effort avoid writing code behind esp in wpf app - should fusion of both out of it.
1. designer perspective
uis built designers using designer tools (expression blend , friends). if have kind of worklow, doesn't work if put significant amount of ui-related code in codebehind. @ least that's experience made. code , behavior/functionalty defines inacessable designer:
- for part code executed @ runtime , not while designing. designer doesn't see full story while designing.
- designers not programmers , have limited (if @ all) porgramming skills incapable of refining ui behavior defined there.
additionally have made experience gets quite hard find way provide mocked designtime data (d:designinstance, d:designdata, d:datacontext
) designer work if there codebehind.
2. developer perspective
ui-related code in codebehind (i assuming here unnecessary talk odds of putting domain logic in codebehind) code not reusable. code bound forever 1 specific usercontrol/window/page. if example instead write custom attached property or behavior resuablity plus make our desginers happy because can use too.
all code put in codebehind code hard test. of course doesn't easier putting in xaml or in custom attached property. depending on type of functionality put in codebehind there cases have encapsulate in testable (reusable) classes.
defining appearance , behavior in xaml tends less (as opposed questioners argument) error prone in code. can't make many mistakes in xaml can in code. if did wrong chances see right away in designer/visual studio. of course tools still can improve here. infact if additionally use resharper "incorrect spelling" miskates in xaml questioner mentions impossible make. code highlighted right away. sure standard tools pick up. xaml preferred way define ui in wpf , higher effort has been made microsoft assure works expected using code. infact have spent quite time debugging memoryleaks , runtime exceptions on code did ui related stuff , have been moved xaml little or no effort.
if ease on codebehind abstinence there higher risk write clutterd , bad code. tempting put quick hack in codebehind. have sufferd consequences more once.
using codebehind necessary. once used viewmodel driven uis there alomst never justifyable necessity codebehind. doesn't take effort put somewhere else. why bother?
Comments
Post a Comment