How to create different .cs files - c#

Is there a way in WPF for the events (such as Click) to have the method in a different .cs file rather than the MainWindow.xaml.cs (for instance)? In other words, when i go to select the mouse down event and double click on it to write the method - the method appears in MainWindow.xaml.cs .. is there a way to redirect this to another file? I would need access to all of the attributes/fields that i use (such as textboxes, buttons etc) that are on the MainWindow.....
In my MainWindow.xaml, I' have methods dealing with gotFocus and lostFocus etc. I don't want to be dealing with sockets and connection within the same file (as I feel that is bad design). Correct me if I'm wrong.

If you really wanted to, you could create a Partial Class
to put your event handlers in. It will still be part of the MainWindow class, but it will be in a different file.
That said, a better design would be to move your code for dealing with sockets and connections out into its own class or classes, while leaving the event handling code in MainWindow.xaml.cs. Partial classes aren't really the right tool to use in this case, IMO.

it sounds like what you want to do is use a MVVM design pattern (WPF lends itself very nicely to this, BTW).
here is a good article on MSDN,here is one by Josh Smith, and a google will reveal much more
it sounds like you need to look into commanding as well

If your notion is to remove the dependency between the UI and Codebehind then probably the best idea, since you are using WPF is MVVM pattern. So you that your view doesn't have to know about what is happening when you click on the button etc. Or else you can event think about ICommand to separate the commanding from your code behind. exactly something like #Mead'Dib has recommended.
The other area which you can explore is to think about something like Command Pattern where you can separate the Receiver and invoker. So that you are not tightly coupled with the code behind. So just think about using some kind of pattern that will make you safe when maintenance issues there.

Related

Is it ok to use click events for small operations in WPF (MVVM)?

I have a WPF application implemented using MVVM. But for some small operations, such as scroll, confirmation box button click, left click operation, right click operation, etc, I am using click events directly in views.
I know MVVM does not recommend this, but is it ok to have such click events or its a bad coding practice while using MVVM? What are pros and cons of using this?
the MVVM pattern gives you:
Seperation of concerns (which is true for all UI patterns)
Unit testing of view logic, by executing the view-model without the view.
Developer-Designer workflow, allowing designers using Blend to work on the same code.
If handling UI events in code behind doesn't prohibit the above, then there is no problem. Personally I use commands if I can, but am not concerned if there is a little code-behind required.
Events can be used, but the problem with allowing codebehind events is that it's a slippery slope. you add one thing, then you add another, and all of a sudden you create actual logic in the codebehind class. (It's even more prominent if you are working with other less experienced programmers in your team).
That's why some programmers prefer, to almost no exceptions, to not write codebehind AT ALL.
Every code that fits the codebehind without being really application-logic code can also be written within a Behavior, which makes the architecture much more strict and simple to define.
If your button does something that is specific to your UI then yes you should use event handlers over commands.
e.g. If you have a button that scrolls a ScrollViewer control to the bottom then it would be bad practice to use an MVVM style command as your ViewModel would need knowledge and direct control of the view. For these situations the view should be self contained.
If your button needs to do something with data then you should use a command and perform the operation in the ViewModel.
I fully agree with #Noam M. Just to extend his answer:
Whether it's violation of MVVM or not depends on what you acually do in eventhandlers. If it's logic that is covered by the view responsibility, it's perfectly ok.
For example, PasswordBox password property cannot be databound, because it is not DependencyProperty and using PasswordChanged eventhander to set viewmodel property is perfectly ok. However, if you wrote password validation against server, that would be violation of mvvm.
I often use Loaded/Unloaded events to call Activate/Deactivate methods on my VM. When I use it too often I create behavior implemented as attached property, that does it for me, so I don't have to repeat the same code in code behind multiple times
I often use DataGrid's events in codebehind, like sorting etc.
I use TextBox.GotFocus event to select all text. Again, I create behavior when I need to reuse it.
I use codebehind to trigger, or create animations if it would be too complicated in xaml. In that case I just leave comment in xaml for other developers.
In MVVM application not all assets must be strictly written using MVVM. For example I have just written my ModalDialogWindow, where I inject content and buttons. I don't have viewmodel for this control and I do everything from codebehind. However, my application has solid MVVM architecture and I show modal dialogs from my page viewmodels using IDialogService. The ModalDialogWindow does not break testability, blendability, or readbility of my application, because in test I mock the IDialogService anyway and I don't need to test ModalDialogWindow UI itself.

Is it an antipattern to use both traditional click events and ICommand?

Generally, I think it's good practice to use ICommands to handle button clicks that need to do something (such as save user input). However, when the button does something strictly on the UI, like open a modal dialog, the view model doesn't need to handle that, or even be aware it happened. In such cases, it seems like it makes more sense to just use the button's Click event handler, but mixing and matching like that seems like a potential anti-pattern. Am I correct in thinking so?
For example:
var openModalButton = new Button();
openModalButton.Click += OnModalButtonClick;
//Elsewhere in the view...
var saveInputButton = new Button { Command = _vm.SaveInput };
It's not inherently clear by looking at the code why one uses a command, and why one uses a click event.
Jedediah,
I usually do as you and mix and match. Usually (for me) there is only 1 or 2 cases like this, and the idea of patterns and architecture is to make the code easier to read and simplify things. Adding a lot of code just to ensure the MVVM pattern is followed seems like it complicates things in this case. That said, the way I've seen this usually handled is bind the button to your ViewModel with ICommand, and then use a "mediator" or "service" to launch the dialog. You could do a Google Search on: "HOw to handle opening a modal dialog the mvvm way " and/or see:
Open dialog in WPF MVVM
The "pretty" way to make a modal dialog in WPF with Prism and MVVM Pattern
Handling Dialogs in WPF with MVVM
Good luck!
Dave
Of course consistency is important as Robin pointed out. However there are scenarios when you'd not want the ViewModel to be involved. Then there's no choice and I think it is much better to break consistency here but not to break the pattern (MVVM) by handling stuff in the ViewModel that is not its job.
You took modal dialogs as an example and I do not agree that the ViewModel should not know about it. Of course the ViewModel is not allowed to directly open that dialog, settings its owner and the likes. But the dialog most probably is part of the workflow and it's just fine to know about the current state of the workflow in the ViewModel. So there should be a layer in between. A service or something similar that allows you to say "I want to show the UI for X" and that solves this by using a modal dialog. The ViewModel doesn't know about the modal dialog but it knows the current state, for example that it is asking the user whether to save changes. Of course this requires some kind of infrastructure handling the special cases and tricky parts. MVVM frameworks offer solutions for this.
If that sounds like overkill for your application simply put that event handling in the code behind of the view. It is not beautiful style but it does not break the MVVM pattern.
In one phrase: Better to mix than to violate the pattern.
I think it is an anti pattern, or not very cool thing at least,first because you're mixing the two approaches and that's not consistent, secondly because I believe that that needs always to be handled in a Command instead of an Event handler, why ?
the view model doesn't need to handle that, or even be aware it
happened. In such cases, it seems like it makes more sense to just use
the button's Click event handler
Not really, additionally to the fact that Commands help you separate your object from the logic that executes the Command thus it makes it loosely coupled, but it also help enhancing the reusability of your code, for instance someone in the future may want to change that button into a whole new control that might have a different event, and different args for the corresponding event ...
and that breaks your code, using a command however is better and is always compatible and reusable.
Moreover, Laurent Bunion explains in this article how Events are problematic :
For all their utility, event handlers have one problematic side
effect: they can create a tight coupling between the instance that
exposes the event and the instance that subscribes to it. The system
needs to keep track of event handlers so that they can be executed
when the event is raised, but the strong link this creates might
prevent garbage collection. Of course, this isn’t an issue if the
event handler is a static method, but it is not always possible to
handle all events with static methods only. This is a frequent cause
for memory leaks in .NET.
Another consequence of the tight coupling between an event and its
handler is that the event handler for a UI element declared in XAML
must be found in the attached code-behind file. If it is not there (or
if there is no attached code-behind file), the compilation will fail
with an error. This is especially an issue when working with list
controls and associated DataTemplates. When an element of the template
must be actuated, an event handler can be defined, but as a
consequence, the DataTemplate cannot be moved into an external
ResourceDictionary.

WPF MVVM Code Behind

I try to avoid code behind in views, within my WPF MVVM project.
However I have some things that are very specific to the view. For example when a control gets focus I want the full text to be highlighted (even if a user clicks into the text box).
Here I have a choice to handle this in the view model (which would then need to know about the view, which I want to avoid).
I also have some other code like that does things to the UI when the user presses up down left or right on the keyboard (and they only make changes to the view, not the model or viewmodel) and again I'm thinking the best place for these is in the code behind of the view.
So I'm asking if the code only affects the view (e.g. things like cursor movement, selecting all text in a text box etc..., and not the model or view model, is it okay to put it in code behind, rather than elsewhere.
Wondering what is best practise here, or if anyone else has a better suggestion where to put this code.
So I'm asking if the code only affects the view (e.g. things like
cursor movement, selecting all text in a text box etc..., and not the
model or view model, is it okay to put it in code behind, rather than
elsewhere.
Not only it is OK, but it is strongly encouraged.
MVVM is not here for you to write thousands of ugly lines of code in ViewModels, it's here to make the code testable and to introduce a separation of concerns.
If it's purely related to the view (your "focus" example is a perfect example), then just write it in the code behind.
If the behavior is UI related only, then you should not put it in the ViewModel. The highlighting example you gave is a good example of such a case. Having said that, I would suggest you avoid repeating your code by (for example) creating a custom control that highlights the text when it has the focus. This way, you can reuse the control in as many views as you can, your views stay free of codebehind, and if you optimize your control, the optimizations happen across the board.
EDIT:
In light of Ravi's answer, Behaviors are also a way to introduce UI related logic while leaving the View free of codebehind. However, if you are finding yourself repeatedly declaring the same controls with the same behaviors, in my opinion it is better to create a control that incorporates the behavior.
That being said, if said UI logic is going to appear only once in one view, you may consider putting it in codebehind. Although it is quite rare to know in advance that you are not going to need that logic elsewhere.
EDIT:
I think #ken2k 's use of strong encouragement refers to not putting it in the ViewModel, which I also advocate. UI logic should be implemented in the View, as he says. Now, there are a few ways of doing that. One of these is coding it directly in your codebehind, which can lead to repetitious code and maintenance issues. Also, if you employ unit testing, it could put you in a difficult spot. The second is coding such logic into behaviors, which is a good way to encapsulate UI code. You can then unit test the behavior to make sure it works OK. However, you can find (as I did, in many projects) that you have started to pepper every TextBox in your XAML's with behavior tags. If that starts to happen, I would (and have) create a 'HighlightedTextBox' control and use that in my XAML. In summary, my suggestion does not contradict ken2k's, but is a pointer in the direction of resolving some issues you may have when placing logic for your View.
Using Custom controls as #Boluc Papuccuoglu suggested, is good option but before using that i want you to take look here Behaviors in WPF introduction
It is strongly recommended to have all your view stuff logic at one place. Instead of polluting ViewModel you should always keep View stuffs in XAML and code behind.
ViewModel responsibility is to contain only data part which can be unit tested. With UI stuff in ViewModel, you will make it hard to be unit tested.
As per link here at MSDN, definition of code behind:
Code-behind is a term used to describe the code that is joined with
markup-defined objects, when a XAML page is markup-compiled.
As you can see, code behind is partial class of your view. One half is declared via x:Class attribute at root element and other half in form of code behind. So, as per me all UI stuff should be at one place and you should not think twice before placing the view stuff in code behind. (that's what it is meant for). MVVM never meant design without any code behind.
Also ViewModel responsibility is to just provide data to your view via data binding. It should never be aware of UI stuff.
Read more about it here - Code behind and XAML in WPF.
How much of your code do you want to unit test? If your view can trigger a command when a control gets focus and your view model can programatically fire an event to highlight the text in that control then you have everything you need to unit test that behaviour with mocked objects. And even if you don't want to unit test (or can't because the bean-counters at your company won't give you the time/budget to do so) then placing that functionality in attached behaviours means they can be used elsewhere. I'm not quite the hard-core MVVM purist as some others on this site but I can honestly say that even in the largest enterprise applications I've worked on I've never once seen a case where WPF code-behind was absolutely required.

How to get data from TextBox, which located on the other page?

I have MainPaqe.cs (MainPaqe.xaml) and Periodic_Request.cs (Periodic_Request.xaml), in addition, Periodic_Request.xaml has TextBox with name TxtBlock_numRequest and Combobox with name CmbBox_lvlPriority with possible 3 options.
The problem is how get user written numbers or strings from TextBox and Combobox in the MainPaqe.cs. I need to get all this information after pressing button.
Someone has advised to use MVVM , but honestly I can`t understand it. This is why I need your help.
MVVM is an architectural design pattern which facilitates the Separation of Concerns design pattern. It is highly advantageous to make use of the MVVM pattern when developing your WPF applications although not compulsory. Implementing the MVVM pattern in your application can require a little more effort and thought, at least when first using it, than is required when using WPF the old WinForms code-behind way.
1) If you want to go down the MVVM route, take a look at the EventAggregator and Mediator\Message Bus patterns. These allow classes to communicate with one another without them requiring direct knowledge of one another.
2) Alternatively if you are happy to continue using the WinForms route, take a look at the EventHandler<T> delegate. This will allow you to raise an event in one class which can be detected by another class.

Are WPF and Silverlight command implementations useless for the M-V-VM (M-V-P) pattern?

Please excuse my ignorance, I only started coding in Silverlight recently.
I tried implementing the command pattern in Silverlight and hit a wall.
They say commands are great, because you can write them into xaml, so you can keep your code-behind clean, also you have loose coupling between your view and your viewmodel because there is no direct reference to the viewmodel in the view.
You can not keep your code-behind clean, because you can bind only one command to a control, and you have to decide which event will fire your command when you bind it. If a control has 30 events, you have to choose one for commanding. The other 29 will execute the other commands from event handlers from the code behind.
Loose coupling can be achieved more simply by dependency injection, commands add a useless layer of indirection that gives nothing extra, they only make it a bit harder to maintain your code. It is easier to maintain your code, when you are programming against an interface and see exactly what method gets called, then when you have to keep jumping between your command definitions and your viewmodel.
Did I miss anything, or commands are really not meant to be used for view and viewmodel interaction?
Please see the following question. This is why I don't get all the hype with commands:
How should I handle multiple events per control w/command pattern using MVVM in Silverlight?
Take a look at Prism (http://prism.codeplex.com) and their DelegateCommand<> infrastructure. Its a good solution for Silverlight and WPF to create commands in the ViewModel (or Presenter) and bind directly to it. Also in Silverlight 3, Behaviors can give you some of this same XAML-based syntax.
SL 2.0 is not so powerful as WPF, you will have to write some code behind :-(.
Not sure if you have read this article about MVVM and SL, talks about commands limitations on SL:
http://msdn.microsoft.com/en-us/magazine/dd458800.aspx
I believe that you could trick your event handlers with attached behavior pattern.
Please see following url for more information:
http://www.codeproject.com/KB/WPF/AttachedBehaviors.aspx

Categories

Resources