contextsensitive RoutedUICommand.CanExecute, Execute - wpf

I have a single RoutedUICommand that can be accessed through various places in the UI. Such as global Keyboardshortcut, Menu, ContextMenu or Button. The code that is to be executed in the RoutedUICommand.CanExecute and RoutedUICommand.Execute methods depends on what UI element was used. How can I achieve this differentiation. I was thinking that I could use the (Can)ExecutedRoutedEventArgs.Source or OrigianlSource but the source is always the same. It is the main Root window. How is this usually achieved? What could I possibly be doing wrong?

If you need different code to run depending on the UI that invoked the command you are probably doing something wrong.
If you have something like a just doing something from a keystroke or opening a dialog asking for more information from a menu you should break this apart into two commands (like MS Office "Print" and "Quick Print" commands).
If you truly have to do different things from each UI element you are not getting any advantage from using commands and should think about using old fashioned event handlers, at least then the element specific code is tied to the element and not stored in a central all encompassing "Execute" code .
And if you choose to ignore my advice above, take a look at the CommandParameter property, you can set a different value fro the parameter for each UI element, at least with it you can keep an illusion of the UI/Logic separation commands are designed to provide.

Normally you could have different CommandBinding implementations for different 'Targets' - having different behavior for each 'Source' is unusual.
Could you give an example of what you are trying to do?

Related

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

Is re-use of commands from the WPF command library a bad idea?

WPF provides a library of pre-defined commands (ApplicationCommands.Save, NavigationCommands.NextPage, etc.) that we can create command bindings for in our own application. I know that it is possible to create multiple command bindings for a single RoutedCommand/RoutedUICommand to obtain different behavior depending on the application context by specifying different executed handlers.
As I understand it, the purpose of the RoutedUICommand is largely to provide a common semantic reference. ApplicationCommands.New, to quote the MSDN documentation, "indicates the intention to create a new item." This command could be used in the command binding to create new items on several unrelated forms within an application.
I hardly ever see this sort of re-use being done. In code online and projects that I have worked on I generally see a RoutedCommand defined in the codebehind or viewmodel named something like 'NewEmailCommand'.
I see several advantages to re-using commands:
RoutedUICommands generally have the Text property defined, so a menu item Header doesn't need to be defined.
When the command has an input gesture defined, there isn't a need to specify an input binding every place that it is used.
When the command has an input gesture defined, the InputGestureText in menu items is automatically populated.
Using the same command promotes consistency across the application-- both in the labels used for the command and the key/mouse bindings.
A few possible disadvantages that come to mind:
A command may be ambiguous in some situations. For instance: you may need two different 'New' commands in one spot (New->{Project..., Web Site...}).
Instead or re-using a command, one might want to instead re-use a command binding that uses static handlers.
ApplicationCommands.New is not a particularly informative command name; it does not tell you anything about the current command handler (such as what is getting created).
I am very much inclined to re-use commands, but as I said: I simply haven't seen it in practice.
What are your preferences? Are there any accepted 'best practices' that I haven't heard about? Are there glaring problems / other benefits to re-using commands?

Passing params through nested user controls in Silverlight 4

I have a three level of nested user controls in my Silverlght 4 application.
the most low level control fires an event with some parameter, then second user control takes the parameter and also fires an event sending parameter to up. Third user controls makes same thing passing parameter to the MainPage. Anyway a have got my parameter but the way I did it very boring and confusing. Is there any acceptable and easy understanding way to do same thing shorter.
Thanks a lot!
That is the correct way, mainly because any level is replaceable and so should function the same way.
Boring and simple looking are actually good things for code... makes it easier for others to follow.
If you want excitement... I would suggest a career change :)
It all depends on what the event is and what the parameter you are bubbling up contains. If this is purely user-interaction and the visual parent needs to react to your event, then, as HiTech Magic mentions, this is the best way to do it.
Now, if what you are trying to do is actually related with the business logic of the application, then maybe your user control is not best place to handle this event and you may benefit from binding a view model to your user controls and using some kind of event aggregator to broadcast your events.
It may be good for you to add more context to the event your are firing and the parameter which you are bubbling up to the container for you to get additional information which applies to your context.

WinForms and child forms - How to consolidate redundant "utility" code?

I searched and Googled first, thinking surely someone must have asked this before, but I sure can't find a good description of this problem.
I have six or eight similar C# .NET 2.0 WinForms applications built with the fairly common model of a main application window with several GUI data fields plus several modal dialogs for further data collection. Many of the data fields (especially TextBoxes) have identical data validation routines. I'm writing the same xxx_Validating() routines over and over, which in the simplest case only capitalize the first character of the entered text (if any) and redisplay the result. I have another one for ZIP Code fields that takes the first 3 digits of a 5-digit US postal ZIP Code and returns the corresponding State, using a 1000-member string array. Simple stuff. There are a few others; here's an example:
public void CapFirstCharTextBox_Validating(object sender, CancelEventArgs e)
{
string strValue = ((TextBox)sender).Text.Trim();
if (strValue.Length >= 1) {
if (char.IsLower(strValue[0])) {
strValue = strValue.Substring(0, 1).ToUpper() + strValue.Substring(1);
((TextBox)sender).Text = strValue; // fires (whatever sender)_TextChanged()
}
}
}
Again this is part of a half-dozen or so such "utility" routines. I've only got one set of these per dialog box class, and all the various TextBoxes in that dialog which need this have their Validating event pointing to the same method. So it's not like I've got 20 of these in a given source file (one for each TextBox) or anything; there's only one for the whole dialog class.
Problem is, the whole set of these exists in every source file where I need them. That's one set for the main window and more for each pop-up dialog box -- and that's too many. I understand modal dialog box classes can't communicate with each other, and making all this stuff global is elusive at best and a big "no-no" at worst.
I have successfully tried passing a reference to "FormMain" (where one copy of these routines exist) to the various dialog constructors, and then calling these validation routines with that from their own validation handlers. It works but feels awfully clunky and certainly not like the best approach.
So, how would I (or would I want to) rearrange the project and organize the code better to have only a single instance of these kinds of things? How would I wire up a global "utility" class of such methods such that I can get to it from the main form's code and from that of a bunch of pop-up modal dialog boxes as well?
I'd like to maintain just one executable with no additional .DLLs if possible (these are all one-project-per-solution, by the way), and if practical I'd like to further be able to share that common code across multiple solutions.
I think the answer will include writing new assemblies, using different namespaces (currently all my code in a given project is contained in the same namespace), and maybe separating this stuff out into its own project in the same solution file.
Is it possible?
You can share code across solutions by keeping the code in one place and adding a link to the file in each solution.
To add a link: right click the project (or folder) you want to add the code to, then select "Add existing item", browse for the file, when found click the down arrow on the button and pick Link to.
This way the projects that link to the file will share the same code.
BTW: take care when using a source control system that doesn't know how to handle these links.

WPF command not executable

I have a button on a toolbar that has its command set to "MyControl.Print" (for example).
In the control the command is added to the command bindings including both the Execute and CanExecute.
The control is within a window with other controls docked appropriately.
I am finding that for the Print button to be enabled I have to "select" MyControl first which does not provide a good user experience and indeed causes various "bugs" being raised and lots of confusion.
Is there a way that I can ensure that the button is enabled whether or not the control has been "selected"?
Since the CanExecute doesn't fire, I think you might be looking at the major downside to RoutedCommands - the way they tunnel and bubble can leave a highly composed interface unable to have commands arrive anywhere useful. For this reason we ended up moving to DelegateCommands from (I think) the Microsoft CAG. Not any of the other stuff, just the commands. Works a lot better, and isn't tied in to the interface so tightly.
Oh, the other response raises a good point. I assumed you meant that to ever print, your MyControl needed to have keyboard focus. Is it only the first time and after that it works?
I recommend http://msdn.microsoft.com/en-us/library/ff921126(PandP.20).aspx as a pretty good starting point. You don't have to worry too much about the IActiveAware up front, since you're hoping for this command to be available all the time (or at least let its availablity be determined by CanExecute).
CommandManager.InvalidateRequerySuggested will force the command manager to re-call all of your CanExecute methods and should disable the button. Perhaps call that onload?

Resources