Is hard coded XAML faster than code-behind generated XAML? - wpf

I have a WPF usercontrol which contains a number of textboxes and buttons. Currently these textboxes and buttons are all created and loaded dynamically into an ItemsControl through the code behind, whenever an instance of the control is created. The only hard-coded XAML is the declaration of the ItemsControl.
This can be a bit sluggish sometimes. Would it be any quicker if I got rid of the ItemsControl and hard-coded the textboxes and buttons into the usercontrol's XAML?

It's generally better to follow best practices for the platform you're working on; generating items 'by hand' in code-behind certainly isn't one of them in WPF. Look into using DataTemplates and leave the hard work for the framework. It's not hard-coding - you will still provide items (in code behind if you must, but preferably through bindings), and the ItemsControl will 'dress up' the items provided into its ItemsSource with the proper DataTemplates. This will usually work faster, even if only because virtualization is handled automatically (depending on the actual control you're using, but most ItemsControls do).

Two options: Use code to generate the object graph, or use XAML.
Code generated:
1) The compiler converts your code to IL
2) Your IL is interpreted at runtime by the CLR
3) Your object graph is created as your code executes
XAML generated (essentially a mix of code and XAML that makes up your UserControl):
1) The compiler converts the code part to IL and the XAML to BAML
2) Your IL is interpreted at runtime
3) Your class is constructed from the BAML file at runtime
4) Unicorns and magic merge the two
The second version is actually a little slower at runtime (or so I've heard). Of course, this is a big simplification of the process, but you can see that the second version is a little more involved and has more unicorn content. But the fact is that they are, from a UI perspective, pretty much equivalent.
I think your slugishness might be caused by something else. Perhaps you're actually seeing the JIT lag from first execution, or other factors in your code may be causing the process to take longer.
Regardless I'd suggest you create your WPF forms the WPF way. Use binding, and if you need to dynamically create your UI look into ItemsControls and DataTemplates. Its much easier than you'd think.

Well certainly there is no great speed difference, but for development, debugging etc code behind is little better.
Try Xaml Generator, and see it for yourself.

Related

Pros and cons of having a WPF specifics in the view model

I'm having trouble deciding what to think about this piece of code:
public SolidColorBrush Brush
{
get { return IsValid ? _validItemBrush : _invalidItemBrush; }
}
It is part of a view model in my current project and as you can imagine, the Brush will be bound to some text elements in the UI, to indicate (in-)validity of other pieces of data, in an otherwise fairly simple and straightforward dialog.
The proponents of this piece of code say that since we're using WPF, we might as well allow for some simple WPF specific constructs in the view model.
The opponents say that this violates Separation of Concerns, as it clearly dictates style which should be taken care of solely by the view.
Please share your arguments, and if you're not happy with the code above, please share your ideas around alternative solutions. (I'm particularly interested in what you have to say about using DataTemplates).
Is it possible that there is one solution that could be considered best practice?
Personally, I would have the two brushes be defined in XAML, and have the controls that use them switch brushes (in xaml) based on the IsValid property. This could be done very easily with DataTriggers, or even a single IValueConverter - the converter could take 2 brushes and a boolean and swap between them fairly easily.
This keeps the business logic presentation-neutral - a "Brush" is very specific to a specific form of presentation, and a pure View choice. Hard-coding this into the ViewModel violates the single responsibility principle as well as is not a clean separation of concerns.
I would very much keep this in the View, and switch based on the IsValid (bound) property that is ViewModel specific.
While there are circumstances where I might use WPF constructs in the view model, this isn't one of them. Here's why:
It's harder to change. If you define brushes as resources and use them in styles, changing your application's color scheme can simply be a matter of loading a different resource dictionary. If you hard-code color values in your view models, you have a lot of different things to change if it turns out your end users need different colors.
It's harder to test. If you want to write a unit test that checks to see if a property is returning the right brush, you have to create a brush in your unit test and compare the values of the two, since it's a reference type.
In many, maybe even most cases, it doesn't make the code simpler or easier to maintain. You're pretty likely to already be using a style (assuming that you are conversant with styles), since they make just about everything in WPF easier. Binding IsValid to brush colors is just a matter of adding a DataTrigger to a style. Which is where anyone maintaining this code would expect to find it.
There are certainly times when I do use WPF constructs in the view model - for instance, long ago stopped wondering if it was problem if a view model exposed a property of type Visibility. Note that none of the above concerns apply to that case.
In cases like yours where it's purely aesthetic I use Triggers or the Visual State Manager to change colors.
Sometimes I do use colors in my ViewModels, but only if its part of my software spec (e.g., the color of the chart displaying a patient's CO2 depends on localization). In that case, I use a Color struct bound property, allowing the View to use the Color for a SolidColorBrush, a GradientStop, or whatever it wants. I initially used a string in #AARRGGBB format to completely remove the WPF dependency but my more seasoned co-workers didn't like that.

masking a portion of a control in wpf

Is it possible for me to mask a portion of a control in WPF?
Your question doesn't really give a lot of detail, but I'm guessing that you want part of a control to be transparent.
Probably the best way to do that is to modify the control template of that control. That gives you complete, er, control over the appearance of that control.
To get the base ControlTemplate of any control, you can either use Expression Blend or XamlWriter to do so - here is a good link that explains both fairly simple procedures.
I don't know what kind of control that you are interested in. Some are fairly simple, some fairly complex, and a majority are in between. Just be careful if you see a control in the template named "PART_something". These are required, and a bit of WPF black magic to make certain controls work automatically.

What's with empty code-behinds?

I understand the benefit to unit testing of preferring the view-model over the code-behind. However, I cannot understand the obsession with achieving completely empty code-behinds. At compile time, the code behind and the XAML are combined, so they are actually the same thing. I, to, love using XAML due to its declarative nature which is very cool. But is there actually any practical reason for insisting that all view-related code be XAML rather than C#?
There are also some benefits in taking advantage of what Blend can do at design-time with XAML but that's really more of a XAML vs (the same code) in code-behind argument. For the no code-behind argument as it relates to MVVM the real goal, as you've pointed out, is to get code moved into classes like ViewModels that can be tested and reused. As with many things, this often gets taken to the extreme and people end up insisting that there never be any code-behind when what is really needed is to have no business logic in code-behind, disregarding that there is also often UI logic too.
XAML is very rich and allows you to do a lot declaratively but there are still UI specific things (i.e. event handlers, some animation handling) that can't be done without using some code. You can usually manage to move this code to some place other than the code-behind by using things like custom controls, attached properties, etc. but if you're not getting any reuse benefits out of doing that it's probably just better to use the code-behind to do that UI logic instead.
Patterns like MVVM are general guiding principles, not a set of strict rules to be obsessively adhered to - those are called programming languages. :)
On good reason is that with WPF and XAML, Microsoft aim to keep separated the graphical and coding jobs. In this way, developer and UI designer can work easilly.
It's all about testability. It's hard (nigh impossible) to unit test your code behinds. With MVVM, you can create test harnesses that fully test your Model and ViewModel.
That being said, I'm a fan of being pragmatic. Some UI events are a bear to set up using Commands, and for those, I'll sometimes drop down into the codebehind.
The view model is the code-behind for the XAML. At least, that's how I think of it. And it's a code-behind file that can be tested without the XAML.
On the other hand, as Ben Johnson might have put it, no man but a fool ever implemented drag and drop in the view model.

What are the real-world benefits of declarative-UI languages such as XAML and QML?

I'm currently evaluating QtQuick (Qt User Interface Creation Kit) which will be released as part of Qt 4.7. QML is the JavaScript-based declarative language behind QtQuick.
It seems to be a very powerful concept, but I'm wondering if anybody that's made extensive use of other, more mature declarative-UI languages like XAML in WPF or Silverlight can give any insight into the real-world benefits that can be gained from this style of programming. Various advantages are often cited:
Speed of development
Forces separation between presentation and logic
Better integration between coders and designers
UI changes don't require re-compilation
Also, are there any downsides? A few potential areas of concern spring to mind:
Execution speed
Memory usage
Added complexity
Are there any other considerations that should be taken into account?
(Updated)
The misconception with XAML is that it's not compiled. It is indeed compiled down to BAML a binary pre-tokenized XAML. Apparently there was a IL compiled version of XAML too called CAML. The OP pointed me to this good article explaining what XAML/BAML and CAML are.
Anyway, to the question why to use it:
XAML is simply a Serialization Format for C# objects that it is particularly well suited to describe hierarchical object structures, like found in WPF GUIs.
What WPF helps you do is write less boring C# code like this:
var grid = new Grid();
grid.Content.add(new TextBlock() {Text = "Hello"});
grid.Content.add(new TextBlock() {Text = "World"});
and just express it in a more readable way like this:
<Grid>
<TextBlock Text="Hello">
<TextBlock Text="World">
</Grid>
Since WPF object nesting (putting stuff inside other objects) can get very deep, WPF makes it much easier to read than the resulting C# code.
As for separation of concerns: XAML helps here too since it does only allow you to express objects and their relationships/properties, rather than logic. That forces you to separate logic from UI layout. The MVVM Pattern is very well suited for this task and allows for eay testability and interchangeable Views.
Added complexity in XAML can be also easily dismissed because the same code in C# gets easily more complex than the XAML markup.
I can't give you any insight into QTQuick though. Sorry
QtQuick is extensible via C++ plugins, actually what the Qt guys recomment is that you do the UI, Animations, Transitions etc in QtQuick/QML while all of your business logic is in C++/Qt. So this way you get the best of both worlds, you can debug your C++ code like you usually do, while at the same time making UIs becomes effortless and extremely easy.
Also another important think about QtQuick/XAML is that they are hardware accelerated, so for example you can get pretty good fps without any effort. So they are not slow at all for what they set out to accomplish.
It saves time, soo much time. I did a UI with code in 3 days, did the same in QML in 2 hours.
The point of declarative coding, i.e. WPF or QTQuick is to provide a separation between the developer and presumably the artist that is implementing the visual aspects of your application. With regards to WPF, I find that debugging gets to be a bit harder. As we speak, I am compiling the latest QT to look at QTQuick. (It takes a long time and I have time to look at stackoverflow :-) ) So, I don't have an opinion on that yet.
QML/XAML are:
Great for MVVM pattern
Hardware accelerated (QML with using OpenGL for Windows, MAC, Linux and Phone OSes... XAML with using DirectX for Windows and its phone version)
Closer to artists
You can create a GREAT and NICE UI using XAML/QML
Easier UI implementation
Nice animation is possible
In XAML, usually you can create a Silverlight version of your application just with a little changes
In XAML there is some great features such as Template, Trigger (DataTrigger, Trigger, EventTrigger), Binding (in any side and also both side together), Resource, Commands, DependencyProperty and Notifiable Properties.
But please note in XAML: (I am a XAML programmer, therefore i have not points for QML)
XAML debugging is not possible
For any change in XAML, all program must be recompile
Be more careful for performance. For example if you use much many RoutedCommands in XAML, your application will be unusable!
In XAML, some feature not works as expected. There is unfortunately some tricks. (It should be clear... should works as expected... isn't it? )
Be careful for some similar namespaces like BitmapEffect and Effect. There is different features and costs. (e.g. BitmapEffect has some effects with software render and Effect has some effect with hardware render)
In real world, artists could not use WPF as Flash (at least with good performance).
Some features works on special places. For example DataTrigger works just in Style tag not in Resource section.
There is some weaknesses in XAML. Some examples: there is not any sequential animation... you cannot do any calculation in XAML (you must write a converter in C# even for a liiiittle work! JavaSript is a great replacement in QML)... some attributes are duplicate. e.g. x:Name and Name... Controlling View from ViewModel is not clear. e.g. closing View from ViewModel (you need some CodeBehind)
Tooooooo much run-time errors. If you use some tags in bad place it will notice you for syntax error, but many of errors occurs just in the run-time. e.g. if i target Background property (instead of Background.Color) for ColorAnimation, it will compile successfully, but in running animation... BUMP... runtime error!!! in such case on Expression Blend, application will crash!!!

Should I be using Expression Blend to design really dynamic UIs?

My company's product is, at its core, a framework for developing metadata-driven UIs. I don't know how to characterize it less succinctly than that, and hope I won't need to for purposes of this question, but we'll see.
I've been trying to come up to speed on WPF, and have been building UI prototypes here and there, and recently I decided to see if I could use Expression Blend to help with the design of these UIs. And I'm pretty mystified at this point.
It appears to me as though Expresssion Blend is designed with the expectation that you already know all of the objects that are going to be present in the UI at design time. But our program generates these object dynamically at runtime.
For instance, a data row might be presented in a horizontal StackPanel containing alternating TextBlocks (for captions) and TextBoxes (for data fields). The number of these objects depends on metadata about the number of columns in the data row. I can, pretty readily, write code that runs through a metadata record and populates a StackPanel dynamically, setting up the binding of all of the controls to properties in either the data or metadata. (A TextBox's Width might be bound to metadata, while its Text is bound to data.)
But I can't even begin to figure out how to do something like this in Expression Blend. I can manually create all these controls, so that I have a set of controls that I can apply styles to and work out the visual design of the app, but it's really a pain to do this.
I can write code that goes through my data model and emits XAML for all these controls, I suppose, and then copy and paste it. But I'm going to feel really stupid if it turns out there a way to do this sort of thing in Expression Blend and I've dropped back and punted because I'm too dim to figure out the right way to think of it.
Is this enough information for someone to try formulating an answer?
I think expression blend is a very good choice ESPECIALLY if you want to design dynamic, datadriven UIs. You can use Blend to desgin DataTemplates that define how a single dataobject is to be presented to the screen. For example, if you have an object of type Person you can define the controls like textboxes, border etc. that then are to be generated automatically for each Person in your list.
You can then fill your ItemsControls (DataGrid, ListView, TreeView ...) with those dynamic databojects and WPF knows how to render them. If a Persopn is removed form the list, the generated visual item will be removed too. This is just a simple example the whole notion of dynamic data is deeply baked into WPF and you can access these features using blend.
To be able to design the datatemplates in expression blend you need to provide sample designtime data.
Also to be effective with all this it is of high advantage if you stick with the MVVM design.

Resources