XAML or C# code-behind
Asked Answered
P

20

52

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?

Platelet answered 16/6, 2009 at 16:30 Comment(2)
Sounds like you don't like learning new languages, which becomes a bad thing for every programmer.Longdrawnout
I think most developers start this way. XAML isn't immediately intuitive, but once you cross the boundary (of understanding) XAML tends to be a simpler approach. And, frankly, I tend to think that simplicity is always the better choice.Cheekbone
B
76

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.

Biogeography answered 16/6, 2009 at 16:34 Comment(12)
Agreed. The beauty of XAML is that it can live outside of compile-time. In other words, it is more like HTML. It becomes very easy to read your XAML from a file in a "Themes" folder, and tweak the UI like a config file. There are some amazing use cases for this. You could never do that with C# (not to mention the security risk it would create)Begin
The down side is that you have to learn essentially two different languages for describing the same thing. I think it's unfortunate that the WPF team decided to use XML for the gui description language. They could have gone with a syntax a lot closer to C#, and thereby made it easier to learn, easier to type, and easier on the eyes. I'm thinking something like JSON, only it would be C#ON. There really isn't a hard line between code and data. Lisp guys understood this in the 70's. Unfortunately XML proponents still don't seem to get it today.Kmeson
@Baxissimo: Wasn't the point of using XML to enable non-programmers to design interfaces?Ethnic
@Phil - Why would non-programmers be more familiar with XML? There's a lot more angle brackets than JSON has :-)Aircraft
@Baxissimo: Because it's easier for humans to read and write than a programming language? Although I think the idea was for them to use blend and then port the interface over to a developer with XML.Ethnic
@Phil, you've got to be kidding? XML is harder to read and write than 99% of programming languages. Don't agree, try giving a 2 page C program and a 2 page XML file to a non-programmer and ask them which is simpler.Maidservant
@Ash: I think rather than asking which is 'simpler' a better test would be to ask them to interpret each. How many non programmers do you think will correctly interpret a 2 page C program compared to a 2 page XML file? It takes training and practise to understand a programming language but XML is just labelled data.Ethnic
@Phil, when it comes to interpretation, comparing your average declarative XML file with imperative C file is not a valid comparison. A more valid comparison would be between an XSLT file and a C file, and that is even more in favour of the C file. In general, my opinion is that XML is highly overrated and has commonly been applied where it there are far better options (Ant, WPF etc).Maidservant
@Ash: Is it still invalid with regards to XAML, which was the original point of this conversation?Ethnic
There is nothing preventing you from separating design and logic in C#. Why does design have to use an entirely foreign syntax from logic?Mortality
@Luke: It doesn't necessarily, but it's helpful that it's in a markup language rather than requiring you to learn programming. A design team I worked with had no idea how to use C#, or how to do even simple programming for that matter, but were very good at designing WPF windows and controls through XAML and Expression Blend.Biogeography
I believe XAML is simpler to understand at first blush.Cheekbone
M
27

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.

Malvaceous answered 16/6, 2009 at 16:42 Comment(2)
+1 on MVVM. Seriously. It changes the way you write WPF/Silverlight code, and makes your code really testable.Begin
I was also going to suggest this video.Gautier
C
15

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.

Cerography answered 19/6, 2009 at 9:54 Comment(6)
I disagree. XAML is a great way to define tree hierarchies as they exist extensively in UIs. Doing so with C# would just get really really messy in terms of indentation. XAML by definition is only a way to serialize .NET Objects to XML and backwards, so anything you do in XAML can be done with c# and object initializers. It's just not pretty and a lot of work.Fibril
You've grasped that the two are equivalently powerful, so you don't entirely disagree. What I think you're missing is that there is no need to have a second syntax, so why have one? To understand this, consider how JSON is often preferred over XML these days. C# initialiser syntax is like JSON in C#. Exactly the same tree can be represented in either, with exactly the same amount of indentation. There are things in WPF (e.g. setting up Grid) where this can't be done in a single expression tree, but that could have been done differently (and can be worked around with simple wrapper functions).Cerography
@Fibril - You seem to imply that XAML isn't really really messy. I disagree. I find XAML to be a mess to look at and work with. At least with code I can step through the debugger, and don't have to wade through a swamp of angle brackets.Kmeson
It's not messy to me. I would like #regions though.Cheekbone
@Kmeson +1 - I find XAML considerably more difficult to read than C# code (or any other language such as C++, VB, MASM, etc.). XML syntax style may be fine for file content that you never have to visually read, but even reading the C# Designer.cs code is significantly easier. Having to read and write XAML to work with WPF is imho just another in a line of bad Microsoft ideas.Outcaste
I feel that XAML is too powerful. And it encourages "boys with a XAML" to try to do everything in XAML. XML is not a programming language.Angelo
J
12

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.

Jinx answered 16/6, 2009 at 16:35 Comment(2)
There are many. Try writing a simple app with some actual behavior, without XAML. You'll see rather quickly where XAML would have been much faster to churn out.Jinx
That's a vague example. But I agree with your answer.Cheekbone
C
8

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.

3. 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.

4. 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

5. 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)

6. 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).

Christman answered 20/6, 2009 at 3:8 Comment(0)
B
5

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.

Begin answered 16/6, 2009 at 16:49 Comment(5)
my vote is for you Brian such stuff is really based on personal interest.Pero
I would think ease of understanding by the maintenance developer should be part of the equation when choosing an approach.Cheekbone
Brian, old answer I know, but isn't XAML just about Turing complete by now? I've just written my first conditional (in a trigger). More to follow probably. Do you really think those do not have to be tested? Programming languages were made to express logic. Mark-up with complex rules to express simple logic… it just does not blend.Sniper
@StevenKramer My views on this have certainly changed in the 4+ years in which I wrote this. Lots has changed. Although I still believe logic should be pushed to a code layer and XAML (HTML, etc) should be as declarative as possible, it doesn't reflect the reality anymore. I haven't played with XAML in years. I use Angular.js now, which has conditionals and flow control (ng-if, ng-repeat, ng-switch, etc). UI tests become much more necessary once we introduce concepts like these.Begin
Thanks for the clarification! I think I'll be pushing as much logic as possible into my code then.Sniper
C
4

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.

Chappell answered 19/6, 2009 at 9:42 Comment(1)
For years I have maintained a separation between my data and logic, and my interface forms and controls -- in C#. It is really easy to do. No XAML was ever necessary. I code this way so that my interface can be changed if I choose. XAML just smells of Microsoft trying to force everyone to web-syntaxed web-based web-hosted cloud apps, which do not work on the desktop.Outcaste
P
4

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

Pauwles answered 21/6, 2009 at 5:24 Comment(2)
What if Blend spat out C# rather than XAML? Would it really matter to your designer? Is there some reason Blend couldn't do this?Mortality
@Myself I suppose it would be non-optimal to have designers spit out every different .Net language.Mortality
E
4

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)

Eohippus answered 15/9, 2010 at 18:41 Comment(0)
M
3

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

Mottle answered 16/6, 2009 at 16:53 Comment(0)
P
2

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#

Plutonian answered 3/9, 2010 at 7:46 Comment(0)
D
1

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.

Devilfish answered 16/6, 2009 at 16:33 Comment(0)
B
1

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.

Benedetto answered 20/6, 2009 at 3:47 Comment(0)
C
1

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.

Capers answered 31/1, 2012 at 13:5 Comment(0)
K
1

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.

Kegler answered 29/1, 2015 at 19:35 Comment(2)
Isn't this example a little disingenuous though? I mean, I would actually write the C# version like this (with proper indenting, which I can't do in the comment): ContentPanel.Children.Add(new Button { Width = 160, Height = 72, Content = "Click Me });. That's one line that I personally find much easier to read than all the angle brackets. I'm not weighing on the "use or not to use XAML" question - I just don't like example comparisons that aren't fair.Omer
Maybe it is, I work on a Windows Forms project that uses a few hosted wpf elements, the actual comparison on my mind when I wrote the answer was that my .xaml files are much more readable than my .designer.cs files. My point was that xaml was designed for this purpose (represent declarative code) while C# is general purpose.Kegler
J
0

Some things are easier to maintain or debug in code.

Jeffries answered 16/6, 2009 at 16:40 Comment(1)
I think I need an example. What is easier to debug in code that can be done in XAML?Begin
T
0

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

Touchmenot answered 16/6, 2009 at 17:13 Comment(0)
P
0

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.

Pharyngitis answered 24/6, 2009 at 15:44 Comment(0)
R
0

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.

Ruphina answered 7/5, 2012 at 19:17 Comment(0)
B
0

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

Bisset answered 6/7, 2020 at 20:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.