XAML or C# code-behind

C#WpfXamlCode Behind

C# Problem Overview


I don't like to use XAML. I prefer to code everything in C#, but I think that I am doing things wrong.

In which cases it is better to use XAML and when do you use C#? What is your experience?

C# Solutions


Solution 1 - C#

Creating an entire window in C# can be a mess of code. The best thing about WPF is that XAML allows you to separate your design from your logic, making for much easier-to-read code.

I'll use C# when I need to create dynamic controls, but I tend to keep my general design, static storyboards, styles, datatemplates, etc. in XAML.

Solution 2 - C#

Check out this video on MVVM in WPF. If you want wrap your head around how to organize a WPF application vis-a-vis what goes in XAML, code behind and other abstractions, this is a great place to start.

Solution 3 - C#

You can certainly go too far with XAML. Those who want their entire user interface (including logic, event handling relationships, etc) defined in XAML are probably missing the point.

The aim of XAML is to provide a common format for determining how things should look. It should just be a description of how to lay things out, how to color and style them visually.

There is really very little point in trying to use it as a replacement for other aspects of C#, because C# has a permanent head-start in terms of programming features - reuse (defining types and functions), referring to variables, procedural programming, and even declarative or functional styles.

Personally I really like throwing together a UI with a Linq expression!

The ultimate absurdity was reached by a sample I saw where they used workflow actions as the children of a button to supply the Click handler, so the whole program was in XAML. It sounds "cool", but the problem was that it was significantly more ugly and unreadable than the equivalent C# or VB.NET program, and so everything that is ready to use in C# has to be replaced by a more verbose, flaky equivalent. Nothing has actually been gained by this translation to an uglier syntax - it's the same program only more hideous. XML is a poor basis for the syntax of a general programming language. Start with the fact that the greater-than symbol has to be written as >!

In a parallel universe, Microsoft released C# 3.0 before they finished XAML. The XAML team adopted C# 3.0 object/list initializer syntax instead of XML as their syntax. And this whole debate never happened.

Solution 4 - C#

My experience is that some things are far quicker to do in C#, while most are quicker to do in XAML. When it takes 5 lines of C# code to do what a single line of XAML code can do, it's pretty easy for me to choose which is better.

Solution 5 - C#

Basically, XAML is meant for expressing visual-design, C# is meant for expressing logic.

Any visual design should be done in XAML, any logic should be implemented in C#.

  • This enables giving the visual design to a designer to play on without worrying about changes to the logic and even replacing the entire visual design at run time using loose-XAML.

  • This also means you could replace either the logic or the visual-design without "breaking" either.

  • The connection between the two should be done with data bindings and with command bindings.

    The practice I use is:

  1. Define the model (the business data object model) in separate C# code.

  2. Define the constant parts of the view (the constant parts of the graphical user interface, e.g. the windows, menus, ...) in XAML (preferably use Blend and not VS for this).
  • Do not define styling (colors, fonts, ...) here.
  • Do not write event handlers for buttons (in most cases) in code-behind-the-XAML, use command-bindings instead.

  1. Define how the model is presented within the view (the GUI for viewing/editing the data objects) using XAML "ResourceDictionary"s located in separate files.

  • Write using blend then add bindings to XAML using VS (Jetbrains' Resharper add-on for VS will help with binding expressions).

  • If the object types are not known during design-time you can use "loose-XAML" and place the XAML in a folder which can have files added to / edited within without recompiling.

  1. Create a connection between the model and the view (a controller/view-model) in C# which:
  • Creates views as necessary (for dynamics objects)
  • Data-binds the view to the model (sets view's DataSource as the relevant object within the model)
  • Implements the commands
  • Command-binds the view to the command implementations within itself

  1. In Application.xaml delete the StartupUri="MainWindow.xaml" and add Startup="ApplicaitonStartUp" instead.
    Within the ApplicationStartUp() event handler:
  • Load any loose-XAMLs you have
  • Create the controller
  • Create the main window
  • Create the model
  • Connect controller to model and main window
  • Show main window
  • (Save model, controller and main window into private fields here to make sure they are all kept alive)

  1. Add styling (colors, fonts) to a separate XAML file under a ResourceDictionary (using blend for this or purchase a ready made XAML theme/skin file).

Solution 6 - C#

The urge to want to write your UIs in C# instead of XAML is really just a manifestation of how comfortable you are in XAML.

For me, is is a personal goal to write as little code-behind as possible. Quite simply put, code behind is hard to unit-test, but can (and usually does) include logic that doesn't get tested. XAML is declarative (like HTML) and doesn't include any logic, so there is nothing to unit-test. I keep my view code in XAML and I keep my view logic in my ViewModel (MVVM) which is VERY easy to test.

Once you become more comfortable with XAML, the more you will realize its benefits over view construction in procedural code... Using a pattern like MVVM, you take it a step further, and realize that code-behind is only useful in rare cases.

Solution 7 - C#

The most important thing to bear in mind is that XAML is for presentation. All your presentation should be in the XAML. If you have logic, you keep that out of your XAML - in your C#.

Imagine swapping out your XAML file with one that LOOKS completely different - but still uses the same data - that's where the division should be.

Solution 8 - C#

One of the nice things about XAML is the separation of presentation an logic. This separation is not just theoretical but also practical. I my case, most of the my UIs are now being handled by a designer. This designer uses blend and does not know C#, has no interest of learnning c#, and frankly should not need to. This designer is a true designer, an artist, that knows how to use those tools to make things look really really nice. Basically my phylosipy is this, the more I use XAML, the less work I have to do on the UI because he can do it. This has worked well for us. I usually design my control to be lookless, give them a basic no frill look, use the DataContext to bind my object(btw DataTriggers are a great way to cut down on code). As a result, I will often checkin my code, come back the next day, synch it, and the UI will look completely different, but everything still work!!!

Of course, it took at least 1/2 year to get there, but now this model seem to work and our UI look Kick A##, our application earns high praise, and I do little work on the UI itself and get to work on cooler things. To make a long story short, I think the code behind might be a bit more developer centric and forgets a whole other group that can benefit, trive, and make a living using WPF, namely the designers.

Of course, there are still times when it takes a devloper to make XAML/WPF sing and dance, and sometime we need to educate the designers about the right way to do things, but I think its worth the investement pays off many times over in large scale projects (maybe not so in short one0

Solution 9 - C#

XAML , MXML all these stuff works as long as you are developing a simple UI with some average complexity . Once your UI gets complex and richer , the automatic data bindings will cause more trouble than their benefits . The purpose of XAML is not make programming easy , it is to seperate UI from logic so that tooling of UI can be easy ..

No Data bindings , No Event handlers .. assume that you will never see your XAML again and write code ..

XAML is presentation . Data binding is not presentation . its presentation logic. put all presentation logic in code behind (data binding and handlers). Developers own code behind , Designers own XAML . if you are a developer and if you are touching XAML , then move that part in to code behind .

we can write WPF apps without XAML too ..

Thanks Vinoth Kumar R (Had gone thru enough using Flex MXML data binding)

Solution 10 - C#

It's not just about you, it's also about your team, some of whom may be designers.

Solution 11 - C#

XAML and C# is a really good way to separate the logic from design as already described.

For a typical programmer the way of programming is really changed by using WPF, assuming that the programmer comes from a C++, VB, WinForms, ATL and MFC background, a background from were the UI was not as natural separated from the logic as with XAML and C#.

To get used to this way of programming it takes some time, but getting more and more experiance it gets really effective.

Before starting it is really good to learn the MVVM pattern and to run tutorials to understand the strength of the pattern, and also to get to understand its benefits.

WPF and C# applications based on MVVM pattern benefits:

1. User Experiance and Usability Separating the logic from UI, makes it more natural to have a dedicated designer working on the UI design and animations. In that way the programmer can focus on the logic behind and the technical solution while the UI is designed by someone that knows design. That has been a problem for many software companies, atleast in the industry that the programmers actualy are the once that are designing the UI as well and that has resulted in a lot of support, maintance and in effecive applications.

There is a higher probability that it ends up with more user friendly applications by have a person with Usability background focusing on the usage instead of the technical solution. There is really interesting book abbout such examples, User Interface Design for Programmers, by Joel Spolsky.

By using the MVVM pattern for XAML application there is a good chance we will see more user firendly applications.

2. Maintanence Maintenance, which is cost a lot within software development. It can feel that the MVVM pattern is a big overhead in the begining but while functions are added and the more complex and advanced the application is getting the more benefitial it is. You will see that it is really easy to maintaine such an application. For an overview you can look into this video:

3. Mix of competences Dedicated designer and a dedicated programmer working in a team to achieve a better result is a very good way of mixing competences. Instead of only hiring programmers organizations need to combine the competences to provide the best results.

4. Opportunity for design interested programmers Finally it is possible to implement fancy applications in the Windows environment. If you are a programmer that are interested in design the Microsoft Expression Blend really opens up possiblities to learn and achive fancy, useful applications with a nice design.

There can though be risk using with XAML and C#, MVVM or not, the great possibilities and flexibility it provides can also be a drawback. Letting the programmer loose with this new easy UI environment, the applications may end up with a wide spectra of animations, colors, everything this new environment provides. Remebering how you added UI controls in the C++ and ATL envrionment.

Still the benefits are more and I hope you get some inspiration to use XAML instead of C# for the UI, when getting used to it I am convinced you will like it.

A link to a good tuturial: Tutorial MVVM XAML C#

Solution 12 - C#

I originally came from the Web side of development and am learning WPF/Silverlight at the moment. For me, the XAML model makes much more sense to me than WinForms ever did. I treat the XAML as if it were HTML and the .cs files just like a code-behind.

Solution 13 - C#

I love clean code, the less code I have, the cleaner it is. Code can be written in millions of ways, XAML is more restrictive. XAML is good at cutting down code, when appropriate of course. If I can put something in XAML, I'll do it. Tools can read XAML and do stuff with it. Much less with code. Tools and frameworks handling XAML will evolve and get better, doing more and better work with existing XAML. Can't say that about code. The more XAML evolves, the more we'll be able to declaratively define our applications.

For me, using XAML is like using LINQ. If I can write a one line statement that is easy to read and let a framework decide the best way to implement what I want, I feel good. I definitely try, as much as I can, to use declarations of what I want instead of hardcoding how I want it to be done. F# is another good example of this paradigm.

Solution 14 - C#

All logic should be in code regardless what you programming language that you use in computer programming. XAML should never replace that even in ControlTemplate although it is nice but it is far much easier to unit test and debug code.

Solution 15 - C#

It seems no answers mentioned an important point yet: https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh465340.aspx

> XAML is just procedural code (only easier)

<Grid x:Name="ContentPanel" Margin="12,0,12,0">
    <Button Height="72" Width="160" Content="Click Me" />
</Grid>

"The following shows how this XAML could be partially replaced by code written in C# or Visual Basic."

// Initialize the button
Button myButton = new Button();
// Set its properties
myButton.Width = 160;
myButton.Height = 72;
myButton.Content = "Click Me";
// Attach it to the visual tree, specifically as a child of
// a Grid object (named 'ContentPanel') that already exists. In other words, position
// the button in the UI.
ContentPanel.Children.Add(myButton);

If you worked with windows forms for example, you probably remember the windows forms designer generates a .designer.cs file containing code similar to the example from the link above. That kind of declarative code is much better represented in XAML than C#.

For any non-toy application you should ALWAYS prefer XAML to define UI and connect it to logic in a MVVM manner.

Solution 16 - C#

Some things are easier to maintain or debug in code.

Solution 17 - C#

Not to Mention that you will be able to do more in Xaml2009 that has to be done in code behind now.

Unfortantly BAML won't fully support xaml 2009 in vs 2010 time frame so you can't compile xaml in 2010 time frame. And will have to wait for a later version of blend to do the full dev design loop. (later than 3)

Douglas

Solution 18 - C#

XAML can be seen as being similar to a combination of XHTML and CSS or XML and XSL which are used for structure and design. Any form of logic should be in C#. This way structure and design are seperated from logic. Your code should be cleaner too by using this approach. Another positive thing is that tasks can be easier to separate between designers and programmers.

One more thing... this is the definition of XAML from MSDN:

> Extensible Application Markup Language (XAML) is a markup language for declarative application programming. Windows Presentation Foundation (WPF) implements a Extensible Application Markup Language (XAML) loader and provides Extensible Application Markup Language (XAML) language support for Windows Presentation Foundation (WPF) types such that you can create the majority of your application UI in Extensible Application Markup Language (XAML) markup. In addition, the SDK includes a Extensible Application Markup Language (XAML) editing tool called XAMLPad. You can use this tool to experiment with Extensible Application Markup Language (XAML) in real time.

Link to quote.

Solution 19 - C#

Programming WPF in C# with a fluent style helps keep the code size and complexity down. See this answer for an example of using a fluent style with WPF.

Solution 20 - C#

It's mostly preference I think. I use WPF, since it's easier to structure different screens and separate the C# code logic from the UI. Typically all my logic is structured in another C# library than my UI which is the startup project in WPF or Windows Forms

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser101375View Question on Stackoverflow
Solution 1 - C#Will EddinsView Answer on Stackoverflow
Solution 2 - C#JP AliotoView Answer on Stackoverflow
Solution 3 - C#Daniel EarwickerView Answer on Stackoverflow
Solution 4 - C#John FisherView Answer on Stackoverflow
Solution 5 - C#Danny VarodView Answer on Stackoverflow
Solution 6 - C#Brian GenisioView Answer on Stackoverflow
Solution 7 - C#FentonView Answer on Stackoverflow
Solution 8 - C#jm DucasseView Answer on Stackoverflow
Solution 9 - C#vinothView Answer on Stackoverflow
Solution 10 - C#Kent BoogaartView Answer on Stackoverflow
Solution 11 - C#SunView Answer on Stackoverflow
Solution 12 - C#Rob AllenView Answer on Stackoverflow
Solution 13 - C#devMomentumView Answer on Stackoverflow
Solution 14 - C#RobertView Answer on Stackoverflow
Solution 15 - C#Eduardo WadaView Answer on Stackoverflow
Solution 16 - C#user117499View Answer on Stackoverflow
Solution 17 - C#DouglasHView Answer on Stackoverflow
Solution 18 - C#PartialView Answer on Stackoverflow
Solution 19 - C#dharmatechView Answer on Stackoverflow
Solution 20 - C#LeroyJenkFrettingsView Answer on Stackoverflow