Custom control wpf, enabling invoking control methods to support MVVM pattern - wpf

I am writing a custom control in WPF, and i have a couple of methods in the control that the user of my control can invoke.
Although it can be invoked directly, due to requests from users, i want to enable the control's methods to be invoked in a MVVM manner.
After research, i take it i have to implement ICommandSource on my control.
The MSDN has an example but i find it too much over-engineered for my situation (or maybe because i don;t understand it at all!).
All i want is to let my consumers to call my method via a command rather than put their calling code in view's code behind.
Please advise with a simple sample code to implement this. Thanks.

In the Blend SDK is a behavior MethodInvoker (if my memory serves correct) that allows you to bind to a method. That way you do not have to implement ICommand.

If you have access to reflect over the .NET code (or you can download the .NET source code via download) look into how MS does it with ButtonBase. Yes, there is a lot of code under the hood, but that's because if you're going to create a custom control you should account for both scenarios of RoutedEvents and Commands.

Related

Diffrence between Triggers, Behaviors and Commands in MVVM?

Can anyone please explain difference between Triggers, Behaviors and Commands. I tried to search on this, but could not find anything useful.
And would also like to know in which scenario which one should be preferred and which one is used frequently among them?
Behavior is a way of interactivity without writing code. Behaviors makes interactivity much simpler for the designers. In short, a behavior is a reusable piece that encapsulates some functionality that can be attached to an object to extend its built-in interactivity capabilities.
Commands are used to encapsulate a piece of logic, which various Silverlight controls can bind to and execute in response to an event, such as a button being clicked. You can expose a command from a ViewModel as a property and bind the Command property of a control in the View to it. When the control is clicked, the command will be executed.
In MVVM scenarios, triggers are used to notifying the view of an event from a ViewModel.
For example, perhaps the view needs to navigate to another view once a save operation is
complete. You can implement this behavior by raising an event from the ViewModel that the view can listen for by doing either of the following:
• Wiring up an event handler in the view’s code-behind and writing some code to
respond to the event (Not recommended approach)
• Implementing a trigger in the view that listens for the event and responds accordingly
You can see this, this and this for more explanations.
Also, Pro Business Applications with Silverlight 5 is a very good reference for you.

Silverlight MVVM question

I'm working on a project and learning SL/MVVM as I go. I'm using MVVM light and feel as if I have a decent grasp of things. I understand binding controls to the VM and also sending events/commands to the VM.
A few questions I have:
In an MVVM application how is the Application object accessed from the VM, for calling Application.Install or checking install state? Or do you just stick it in the code behind of a view for that case? I suppose this could be done through MVVM messaging but you'd still register a listener in the code behind.
I'm not sure if this can happen but how would one, from the VM, access a method from a View/Control(s) to do something that can't be accomplished through data binding or commanding/eventing? Is this where Dependency Object/Properties come into play?
The application should provide a service for obtaining the information relevant to the Application singleton; as with any data which could be used throughout the application; yours or the frameworks.
If you are ever needing to access a method on a UIElement/FrameworkElement/Control from the ViewModel that would be the point in looking into a custom Control or UserControl to provide the needed behavior. That is typically solved via Triggers and Behaviors.

How to Snoop proof your wpf application?

Snoop allows you to look inside the application and change element properties.
Its a great asset for developers, but can be a security issue in some cases, like when we have users who like to look in places where they shouldn't be looking. Is there a way to do something to block applications like Snoop from "snooping" your application?
And if there is no way to block it, what do you recommend to do to minimize security risks?
Snoop is a utility that allows you browse visual tree of a wpf application and view and change properties. Its very useful when you are trying to debug something and have no idea what is going on. You can find more here.
Thank you.
There actually is a way to detect whether your application is being "snooped" by the snoop program. The solution I will give is not a silver bullet, and if someone really wants to snoop your application, they'd have to modify the snoop source code (it's an open source project).
What snoop actually does is it injects an assembly into your application, and the injected assembly recursively examines your applications visual tree starting at the root. In other words, snoop actually runs inside your application. That being said, the solution is to raise an event when the snoop assembly is injected into your application.
First, you need to subscribe to the assembly-loaded event somewhere in your application (preferably the begginging):
AppDomain.CurrentDomain.AssemblyLoad += new AssemblyLoadEventHandler(CurrentDomain_AssemblyLoad);
Then, you would implement the handler somewhat like this:
void CurrentDomain_AssemblyLoad(object sender, AssemblyLoadEventArgs args)
{
if (args.LoadedAssembly.FullName.StartsWith("ManagedInjector"))
MessageBox.Show("hey you, stop snooping");//and shut down your application.
}
You would probably need to enhance this solution for real silver-bullet solution, but at least this solution will definitely stop the current latest version of snoop being run as is (without the code modified). The better solution would be to check that no external assemblies are being injected into your application.
However, Kent is still right in the fact that a utility like Snoop should not cause any security vulnerabilities since security should not be implemented at the UI level. But at least this shows you how to prevent people from "snooping" your application.
By implementing security properly. If your "security" can be thwarted with a tool like Snoop, then you're doing it wrong.
Suppose there's a command that only certain users can execute. It sounds like the only place you're enforcing this is at the UI level (by disabling the corresponding button, for example). That being the case, you're right - I could easily use Snoop to enable the button and execute the command. But you should be enforcing the security constraints on your server, or perhaps in your command execution logic if you have no server. Basically, security should be implemented as close to the thing you're trying to protect as possible. Security at the UI level is merely for convenience of the user.
Great responses for a very good question,
I want to add an example of the password that should never be saved in your datacontext, as snoop check also the datacontext of the UI, so if you use the right control PasswordBox you will find that you can’t bind the password property, that means even if you snoop the application you can’t get the password as it is not saved in any property
But we found many people who try to create a work around (helpers, behaviors, usercontrol ...) to bind the password, but they forget that snoop can get it like that
So your server should never trust your client , every time it should check the right privilege (as we can sniff the client request using Fiddler for exp then rebuild a custome request to by pass client application security)

Attach Behaviour Vs Routed Command

What is difference between the two, i am just confused so much on these two concepts and not able to apply correctly?
Attached behaviors is a way of extending controls without having to subclass them! Examples of this is add watermarks to textboxes, forcing textboxes to only accept certain charecters, etc... It is typical stuff that you can do to a control by subscribing to certain events or setting properties! By creating a attached behavior, you are just encapsulating that functionalaty for reuse!
Routed Commands is a way of abstracting away your executing logic for actions like clicking on a button... in WPF, the build in implementation of ICommand, basically walks the visual tree looking for a RoutedCommand that it can execute! The real big diference between these too is that ICommand can only really work on things like buttons... If you need to execute some logic on clicking of a image, you can't without creating a attached behaviour!
Also read up on RelayCommand/DelegateCommand
UPDATE
Attaching a behavior to an object simply means making the object do something that it would not do on its own.
Josh Smith - http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx
In search of a similar question, I came across Chapter 6 of the PRISM 5.0 Handbook, which states as a note on command-enabled controls versus behaviors:
WPF controls that support commands allow you to declaratively hook up a control to a command. These controls will invoke the specified command when the user interacts with the control in a specific way. For example, for a Button control, the command will be invoked when the user clicks the button. This event associated with the command is fixed and cannot be changed.
Behaviors also allow you to hook up a control to a command in a declarative fashion. However, behaviors can be associated with a range of events raised by the control, and they can be used to conditionally invoke an associated command object or a command method in the view model. In other words, behaviors can address many of the same scenarios as command-enabled controls, and they may provide a greater degree of flexibility and control.
You will need to choose when to use command-enabled controls and when to use behaviors, as well as which kind of behavior to use. If you prefer to use a single mechanism to associate controls in the view with functionality in the view model or for consistency, you might consider using behaviors, even for controls that inherently support commands.
If you only need to use command-enabled controls to invoke commands on the view model, and if you are happy with the default events to invoke the command, behaviors may not be required. Similarly, if your developers or UI designers will not be using Blend for Visual Studio 2013, you may favor command-enabled controls (or custom attached behaviors) because of the additional syntax required for Blend behaviors.
For me, this is the single best summary of what’s the difference between behaviors and commands.

Where to put code in (primarily) windowless WPF app?

So I'm planning on writing an application that is largely a windowless application. There will be windows for user interaction, but only at the request of the user. Otherwise the application sits in the system tray and runs a timer, executing some logic every minute or so. My question is this: As far as I can tell, I would put all the related logic in App.xaml.cs (starting the timer, executing the logic at each interval), but for some reason this seems wrong to me.
The app will have a system tray icon that users can interact with to get details, adjust settings, etc., but otherwise the app just sits there and does what it does. Is it appropriate to put all the code in the code-behind for the App.xaml class? I don't know why, but it seems as if I shouldn't, and there should be somewhere else, but I can't really think of anything.
I've never written an app like this before, hence my ignorance. Any advice would be greatly appreciated. Thanks.
James
Even with applications where most interaction is done through windows it's usually a bad idea to put all the code in the code behind. Interactions are often initiated eventhandlers in the code behind but you can put your code in classes you create yourself.
The same goes for applications that do not show a user interface most of the time. Most of the actions will be initiated from the App.xaml.cs but that doesn't mean all the code has to live there. You can encapsulate timers in their own classes that can kick off other code to do work for example. Divide your code up along lines of responsibilities, a window class does UI stuff, domain logic goes into other files etc. That will enable you to create more maintainable applications.
It doesn't sound like the code belongs there, and at most just a call to start the timers.
What does sound like a perfect fit for your issues, is the M-V-VM (Model - View - ViewModel) pattern. As you noteded, it also will 'feel' more correct then attaching logic to your code behind. Using MVVM you can separate your sparse UI into a View, and your code can exist separately in the Model and ViewModel.
I would recomend using the toolkit here, as it also contains good overview documents and a sample you can digest as you create your own solution. Laurent Bugnion has also released a MVVM starter toolkit that you could use to get started.
Also, here is some good stuff to get you started on actually setting up your controls in the system tray.

Resources