WPF UI element naming conventions - wpf

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

Related

Benefits of Custom WPF Controls

I've thoroughly checked the custom controls topic, spent several hours looking into custom controls written by other people. I've written my own custom button, to feel it better. I've read all the google answers around the "why custom controls", "advanced custom controls examples" and such.
My question is, WHY?
Why would I (or anybody) go through 9 circles of hell to create his own custom control, when one can just adjust an existing control to his needs (using styles and templates). I actually didn't find any explanation on google, just tons of examples, mostly from people who sound even less educated than me.
I imagine there IS such need, when talking about some complicated DataGrid with, I don't know, every cell being a button or something (and still I believe I could do it with a regular DataGrid)... But I've not found anything more complex than a beautiful button. Is there nobody sharing a complicated code on the topic?
There are different levels of element customization in WPF, depending what class you extend from. Each has its own uses and is implemented differently. It is not clear from your question if you are asking about a specific type of control or about all of them in general. So, I will tell you what I think about different ones.
UIElement or FrameworkElement
Extending UIElement gives you the lowest level custom control where you have complete control over the layout and rendering. FrameworkElement is slightly higher level as it does most of the common layout stuff for you while also allowing you to override key parts of it. The main idea with these is that they do their own rendering rather than composing other elements together.
I have made a number of custom FrameworkElements over the years. One example is a ruler similar to one you might find in a program like Photoshop. It has a bunch of properties providing customization for how it is displayed as well as showing markers indicating mouse position relative to the ruler (and a number of other little optional features). I have used it in two different professional projects. I think the main benefit is that it is extremely easy to drop in and set properties/bindings on wherever desired. Build it once, use it over and over.
Control
Extending Control introduces the concept of compositing multiple elements/controls into one reusable component via control templates.
I have used this one less often, but still find it very valuable in the right circumstances. Again, the main benefit here is reusability. You create a control with properties that make sense for what you want to do, then hook up those properties to the properties of the controls in it's control template. Really, this is the same as applying a new template to an existing control, with the added feature of being able to define your own dependency properties. You also have the ability to perform custom logic in the control's code if you need to.
I may be misreading some of your text, but you seem to imply that making a custom control is considerably more difficult than making a control template for an existing control. I have found that the two are nearly identical in most cases using this approach, the only difference being whether you have a code behind you can use.
User Control
A user control is really only slightly different from a custom control practically speaking. Only, instead of defining a control template, you define the visual content directly.
This is probably the most common type of custom control. It is basically the standard method for making XAML based content in a WPF application. These can be reused like other controls, but are more suited for single use such as the content of a dialog or window or something else that is specific to a single application.
Some Other Control
You can also extend an existing control to add additional functionality to it. This way, you still get all the features the control offers and only have to implement the additional bit.
For example, I have a custom control called an AutoScrollRichTextBox that extends RichTextBox. So, it does everything a RichTextBox can do. It also has the ability to automatically scroll to the bottom when content is added to the text box (which it only does if the text box was already scrolled to the bottom before the addition content was added).
I could have implemented that feature as an attached property instead of an extension of the control (and maybe I should have), but it works, and I have used it in three different applications (as an output window and as a chat log). So, I am happy with it.
In the end, it really is just a matter of how self-contained, reusable, and easy to drop in you want a control to be. If there is already a control that does what you want, and you just want it to look different, then you should definitely use styles and templates to achieve that. However, if you want to make something that doesn't already exist, limiting yourself to using only styles and templates will make the implementation work harder and make the end result less reusable and more difficult to set up additional instances (unless all instances are identical).
The examples of making things like buttons that look different are not examples of what you should use a custom control for. They are just examples of how someone would go about making a custom control for the purpose of teaching the details of the process. If you actually want a customized button, just customize a button.

C & X11 : how to use graphic contexts

I am confused about "graphic context"s, using the xcb library.
There are some examples around the www, they all show creating one single window with one single graphic context.
Of course when setting up several windows, each will have its own graphicx context, or perhaps several.
Could or should I create several graphic contexts for one and the same window? For example one for drawing flowers, another for rivers, a third for text labels? Or is it better to use only one and adapt it to the job at hand?
What is considered good programming style, in this respect?
You can create as many contexts as you want. The rule of thumb is:
If you draw everything in the same style use one context.
If you change the style, but not very often, use one context.
If you change styles frequently, follow your senses and either use one content (and change its attributes as needed) or create several contents. The latter approach is faster, but if you have too many GCs, you may run out of them (there is a limit on how many GCs a window may have).

Where does angular two-way binding is useful?

two-way binding feature in angular is so popular, and according to angular community it is good when compared with one-way binding.
And there are lots of simple examples to explain how it works.
But my question is where does we use that feature in real applications.
- One example is using with input boxes, other than that is there any good uses of it?
Two way binding as a default wasn't wise because it creates perf issues (~2000 watchers and your app can go bad fast). It led to the introduction of {{::}} binding syntax (bind once syntax) in Angular 1. Overall I can't see where I agree that default two way binding is said to be a good thing by any knowledgeable Angular dev.
I can tell you for a fact, having written an application that displayed many lists of different kinds of objects simultaneously, that default two way binding was a mistake. It created far too many persistent watchers. The community overall seems to strongly agree.
So what you suggest here is correct; there are uses for two way binding. But those needs should be seen as few and far between. And even then, you could probably get around the need for it at all with a little thinking.
For me, two way binding is primarily useful for input fields. But the mechanism is most definitely downplayed now, it should be used sparingly.
Well, when you bind a label with a $scope variable, though the binding is two-way (by definition) it is only relevant in the direction JS -> HTML.
A two-way binding is only fully exploited in cases where the value can also be changed by the user, meaning any type of INPUT component (textbox, dropdown, checkbox, etc.).
One trivial (though one-directional) example is when you have a page that can be displayed in many languages. You would deploy $scope variable all over, and assign to them strings in the current language.
When the user switches language, the simple assignment of the new strings to the corresponding variable will yield the screen to be automatically update to the new language.

Replacing 3rd party Windows Forms UI controls in a large codebase

Me and my colleagues are investigating how to replace 3rd party WinForms controlls by our new UI controls in our large legacy codebase. Practically we would like to replace the 3rd party controlls in the inheritance chain. The 3rd party controlls are used dozens of places by subclassing the 3rd party UI controlls. We d like to perform this change as safety as possible, with minimal code change all over the solution. Do you have any experience how to start? Obviously the inheritance means strong coupling here, so i d like to find the less painful solution here.
Is the "branch by abstraction" concept applicable here?
This is a pretty subjective decision based on your team's understanding of the code base as well as workflow. The bright side is that you've already subclassed all the controls, so you've already done the tedious work of being able to provide whatever properties the code is looking for to compile.
Given that this is WinForms, this should be much more straightforward, since the control sizes and locations are set on the Control level. You need to worry about mapping properties/methods that exist in the old vendor's controls to your new controls and not as much about form layout. This might be straightforward for some controls and more complex for others (i.e. grids).
The biggest roadblock IMO is going to be handling the current design-time serialized logic in InitializeComponent. If you've created a property to map from old -> new, you're going to have to be careful that when the designer re-serializes everything after you open the form and modify something, you might not want to serialize both the old property and the new. As an example:
Old Vendor
this.myOldComponent.Data = this.dataSource;
New Vendor
this.myNewComponent.DataSource = this.dataSource;
In this case, you may consider creating a new property called Data on your subclassed new component so that the old code works without changing anything. Let's say you open the form in the designed and move the grid a few pixels, causing the designer to serialize the data. You might now have:
this.myNewComponent.Data = this.dataSource;
this.myNewComponent.DataSource = this.dataSource;
You can prevent serialization with attributes (good discussion on it in this SO question, but this is just an example of something you might hit.
I don't think there's really a pattern here to follow, unless you mean on the source control level, in which case I would say to absolutely create a new branch apart from your regular development one; who knows what kinds of roadblocks you may hit and you'd want to shelve your work for a bit.
Ultimately, you may decide that it's just best to suck it up and rip out the old components and put in the new, but as mentioned this is very subjective. It's situations like this that make me really love WPF and the MVVM model, since you could entirely rip out the UI and keep the business logic intact.

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!!!

Resources