Not specifying control names in WPF... performance effect - wpf

If you need to access a WPF control from the code behind, you need to supply a Name attribute to it in XAML.
In many cases, you don't need to access controls from the code behind, since a lot of coding logic such as binding is better applied directly inside XAML.
My question is: Is there a performance gain from not supplying the name attribute to controls? Or is it a good habit to give names to all controls on the page?

Yes there is definitely a performance gain from not supplying "name" attributes.
WPF's "Name" mechanism can be useful, but it uses extra RAM and CPU in several ways:
The XAML compiler allocates an extra slot in your class for every named object (4 bytes each)
The XAML compiler adds code to your class to initate each of these
The BAML processor calls back your code to initialize the name in each case
The BAML processor also adds the name to a dictionary, requiring an additional 20+ bytes per name
When looking up names you really need you may run into dictionary collisions with names you don't really need
For a simple control, adding a Name to control can increase the cost of using that control by 5% or so. That's not a lot, but why waste your CPU cycles and your RAM on names that are unnecessary?
Bottom line: If you don't need Names on your objects, don't name them. Usually the content or binding of a control is plenty to identify a control's purpose. And if that isn't enough documentation, you can always use XML comments, which are free.
I'd have to say it is a very bad habit to name all your controls, not just because of the cost but also because it encourages you to refer to your controls by name rather than using proper view model and binding techniques. Most of my XAML doesn't use "Name" for any controls, let alone all of them.

Related

For implementing virtualization in a non-ItemsControl, is it better to retrofit ItemContainerGenerator, or implement simple custom generation?

We're rolling our own special Items-based control/panel combo that isn't based on a subclass of ItemsControl (there are multiple reasons why we can't do this which I won't get into here) but our control does handle thousands and thousands of data items, so we'd like to implement Visual virtualization.
What we're wondering is if it makes more sense to try and bang the existing ItemContainerGenerator class into our design or roll our own virtualization method.
On the one hand, ItemContainerGenerator already handles virtualization and is very efficient, and tried-and-true code is almost always preferable to starting from scratch, but on the other, the ICG was designed specificially for use with, and relies on features of the ItemsControl, which again, this control is not. Plus, that is a container generator but in our case, we just need to generate and lay out a specific, known visual that represents the data item.
Now, perhaps I'm over-simplifying things, but all I see is a need to determine which items would be visible in the ViewPort, ensure visual representations of those items are created, measured and arranged, then discard any left-over already-created visuals. To keep track of it all, it seems a simple item-to-visual mapping scheme is all that is needed, perhaps with a ItemVisual attached property on the DataItem's ViewModel object. That way when an item is removed/destroyed, we just check if there's an existing visual, and if so, nuke it.
That said, can anyone think of a reason we shouldn't simply roll our own visual virtualization? Again, the ICG does this, but I'm wondering if that's taking a Semi to the store to get eggs.

Attention MVVM Purists: Should a ViewModel access localized resources?

I struggle to understand the purpose of the ViewModel sometimes, especially with respect to what it should and shouldn't do.
So... I find myself wanting to expose a display string from my ViewModel. Ok, actually it's a Date string, where I want to display something like "Unknown" if the date isn't set. Really I want a solution to cover the general case, so I don't want a discussion about using null and fallback values. It could equally be a status message like "Awaiting Dispatch" or "Launch Aborted".
So the quesion is, how should the ViewModel expose display strings to the View. The App will need to be localized, so we can't have hard coded strings in the ViewModel.
Is it ok to access the app's resources from the ViewModel, and return the display string?
As an aside, should I be using a resx string resource, or a Xaml resource dictionary? I'm leaning toward the Xaml. Advantages/Disadvantages?
Thanks,
Mark
As mentioned in the other answers, this is clearly the view's responsibility. The view model should expose the data property (a status enum or something similar) for the view to inspect in order to determine the particulars of the display message. From a purist's perspective, generating display properties from the VM or code behind is right out.
I'm surprised to hear no suggestions of datatriggers, though. Use them in your TextBlock to bind to the exposed status enum value and update the text appropriately. This question compares their performance against binding to a converter and suggests that triggers will perform better in this scenario. I haven't done any testing myself, so I'm not sure, but it seems intuitively reasonable to me, provided you aren't listening for an outrageous number of different enum values. I also think it's the more appropriate method in this case, and I'll cite this question asking for a comparison of VC vs. DT use cases, though I don't think it's terribly contentious. To put it another way, if one holds that a VM is a value converter on steroids (a statement which I'm very leery of and will not agree or disagree with at the moment), then this argument holds: a VM shouldn't be exposing display properties; a VM's purpose and abilities are a super-set of those of a VC; therefore, a VC should not be exposing display properties.
I'm doing my best to give the purist's answer (or what I think it is, at least), but there are certainly easier ways to code it than writing a lot of datatriggers, especially if you have many different values to address.
Regarding your resource question, have a look at this MSDN article on resource files, which is, in certain ways, easier to work with than a resx file. Which approach you should use depends on your use cases.
What you are doing is taking data that is inside the system and converting it to a format that makes it more useful and clear to the user. This is the responsibility of the view. It would be the responsibility of the view to format a valid date into the correct culture and it has the same responsibility for any text that you wish to display.
In the same respect the status examples you give would probably be stored as an enum in the viewmodel (since that would make it easier to apply business logic to them, which is the role of the viewmodel) and it would be the responsibility of the view to display the values in a way that works for the user in all respects. This would include size, colour, font, position and culture.
That being said though I have been known to put display logic in my viewmodel (concatenating firstname and surname for example) simply because it is easier. I've even been known to use code-behind (shock, horror!) where it suits my purpose. There is a sliding scale between purity and pragmatism, and it is up to you where you sit on that line.
To display the string Unknown when the date is not set is a display issue and therefore has to be solved in the view. Even "Awaiting dispatch" is a presentation of a value.
So the answer is: The view model should never expose display strings. The view model has to expose a value that leads the view/a converter/whatever object from the presentation layer to choose a display string.
Even if this answer is not the answer you want to read, it is the answer an MVVM purist has to give. And as you asked for MMVM purists, here it is.
For the date, I would have the ViewModel export a nullable DateTimeOffset, where the null value means "not set". The in the View (via a converter or similar), the null value is displayed as whatever you need.
As to the aside: I would use resx. The reason is that there is a defined fallback mechanism when strings aren't available in the language.
An approach I have taken was creating Culture specific Resources and adding instances (singletons?) of these to the ViewModel.
Then the View can simply Bind to the ViewModel.Resource.DisplayString
See this article for Windows Phone 7 which easily translates to WPF.
If you dislike this because you do not want to tie the culture specific resource to the ViewModel and want the View to solve it you could use/write a ValueConverter that turns a value from a VM property into a display string.

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

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.

In XAML, what "guidelines" should I use when deciding whether or not a property should go in a style?

When writing WPF/Silverlight applications, I sometimes struggle when determining whether or not a property should go inside a style or be left directly on the element. What guidelines do you use when deciding?
I think it generally comes down to style reuse and overall project organization.
If it is a style you are going to be reusing across many different elements in a control (such as Brushes) or even in many different controls in your project you are obviously going to want to pull it out into its own resource. For better organization you probably even going to want to put these shared styles in their own resource dictionary file and used MergedDictionaries to pull them in to different controls. You can actually create some pretty useful cascading effects between different styles using the BasedOn attribute as well.
When it comes down just a "one-off" feature of a specific element I think its fine to keep style attributes directly on the element. If it doesn't need to be shared and the style is unique to the one element (specific Border, Margin, etc) it is much easier and more readable to keep it directly on the element.
Very good question. There are two situations where I move a property into a style.
1) Over Crowded Properties - Over crowded properties are nothing but, too many properties for customizing an element. Say for example. If you have a text block and want to customize almost all the properties. Then, it'll reduce the readability. That too if it has somethings like triggers. It'll be too much crowded. By that time, I used to move them to a style.
2) Repeatedly Used Styles - This is obvious case, if I want to apply a same set of properties to be applied for a control. Usually we do this by x:key or TargetType.
HTH

WPF UI element naming conventions

Although Hungarian notation is considered bad practice nowadays, it is still quite common to encode the type in the name of user interface elements, either by using a prefix (lblTitle, txtFirstName, ...) or a suffix (TitleLabel, FirstNameTextBox, ...).
In my company, we also do this, since it makes code written by co-workers (or by yourself a long time ago) easier to read (in my experience). The argument usually raised against doing this -- you have to change the name of the variable if the type changes -- is not very strong, since changing the type of a UI element usually requires rewriting all parts of the code were it is referenced anyway.
So, I'm thinking about keeping this practice when starting with WPF development (hmmm... should we use the txt prefix for TextBlocks or TextBoxes?). Is there any big disadvantage that I have missed? This is your chance to say "Don't do this, because ...".
EDIT: I know that with databinding the need to name UI elements decreases. Nevertheless, it's necessary sometimes, e.g. when developing custom controls...
Personally, I find that WPF changes the rules when it comes to this. Often, you can get away with little or no code behind, so having the prefixes to distinguish names makes things more confusing instead of less confusing.
In Windows Forms, every control was referenced by name in code. With a large UI, the semi-hungarian notation was useful - it was easier to distinguish what you were working with.
In WPF, though, it's a rare control that needs a name. When you do have to access a control via code, it's often best to use attached properties or behaviors to do so, in which case you're never dealing with more than a single control. If you're working in the UserControl or Window code-behind, I'd just use "Title" and "Name" instead of "txtTitle", especially since now you'll probably only be dealing with a few, limited controls, instead of all of them.
Even custom controls shouldn't need names, in most cases. You'll want templated names following convention (ie: PART_Name), but not actual x:Name elements for your UIs...
In my experience - In WPF when you change the type of a control, you normally do not have to rewrite any code unless you did something wrong. In fact, most of the time you do not reference the controls in code. Yes, you end up doing it, but the majority of references to a UI element in WPF is by other elements in the same XAML.
And personally, I find "lblTitle, lblCompany, txtFirstName" harder to read than "Title". I don't have .intWidth and .intHeight (goodbye lpzstrName!). Why have .lblFirstName? I can understand TitleField or TitleInput or whatever a lot more as it's descriptive of the what, not the how.
For me, wishing to have that type of separation normally means my UI code is trying to do too much - of course it's dealing with a UI element, it's in the window code! If I'm not dealing with code around a UI element, why in the world would I be coding it here?
Even from a Winforms perspective I dislike semi-hungarian.
The biggest disadvantage in my opinion, and I've written a LOT of ui code is that hungarian makes bugs harder to spot. The compiler will generally pick it up if you try to change the checked property on a textbox, but it won't pick up something like:
lblSomeThing.Visible = someControlsVisible;
txtWhatThing.Visible = someControlsVisible;
pbSomeThing.Visible = someControlsVisible;
I find it MUCH easier to debug:
someThingLabel.Visible = someControlsVisible;
whatThingTextBox.Visible = someControlsVisible;
someThingPictureBox.Visible = someControlsVisible;
I also think it's far better to group an addCommentsButton with an addCommentsTextBox than to group a btnAddComments with a btnCloseWindow. When are you ever going to use the last two together?
As far as finding the control I want, I agree with Philip Rieck. I often want to deal with all the controls that relate to a particular logical concept (like title, or add comments). I pretty much never want to find just any or all text boxes that happens to be on this control.
It's possibly irrelevant in WPF, but I think hungarian should be avoided at all times.
I like using a convention (just a good idea in general), but for UI stuff I like it to have the type of the control at the front, followed by the descriptive name -- LabelSummary, TextSummary, CheckboxIsValid, etc.
It sounds minor, but the main reason for putting the type first is that they'll appear together in the Intellisense list -- all the labels together, checkboxes, and so on.
Agree with the other answers that it's mainly personal preference, and most important is just to be consistent.
On the need for naming at all, given the prevalence of data binding... one thing you might want to consider is if your UI is ever subjected to automated testing. Something like QTP finds the visual elements in an application by Name, and so an automation engineer writing test scripts will greatly appreciate when things like tabs, buttons etc. (any interactive control) are all well named.
In WPF you practically never need (or even want) to name your controls. So if you're using WPF best practices it won't matter what you would name your controls if you had a reason to name them.
On those rare occasions where you actually do want to give a control a name (for example for an ElementName= or TargetName= reference), I prefer to pick a name describing based on the purpose for the name, for example:
<Border x:Name="hilightArea" ...>
...
<DataTrigger>
...
<Setter TargetName="hilightArea" ...
I prefix any user-interface name with two underscores, as in __ so it is sorted before other properties when debugging. When I need to use IntelliSense to find a control, I just type __ and a list of controls displays. This continues the naming convention of prefixing a single underscore to module level variables, as in int _id;.
You can use the official Microsoft website for Visual Basic 6 control naming conventions, and perhaps combine it with the recommended C# naming conventions. It's very specific, is widely used by developers in C# as well for control names, and can still be used in a WPF or Windows Forms context.
Visual Basic 6 control naming conventions: Object Naming Conventions
C# recommended naming conventions in general: General Naming Conventions

Resources