MVVM Madness: Commands - c#

I like MVVM. I don't love it, but like it. Most of it makes sense. But, I keep reading articles that encourage you to write a lot of code so that you can write XAML and don't have to write any code in the code-behind.
Let me give you an example.
Recently I wanted to hookup a command in my ViewModel to a ListView MouseDoubleClickEvent. I wasn't quite sure how to do this. Fortunately, Google has answers for everything. I found the following articles:
http://blog.functionalfun.net/2008/09/hooking-up-commands-to-events-in-wpf.html
http://joyfulwpf.blogspot.com/2009/05/mvvm-invoking-command-on-attached-event.html
http://sachabarber.net/?p=514
Link
http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/
While the solutions were helpful in my understanding of commands, there were problems. Some of the aforementioned solutions rendered the WPF designer unusable because of a common hack of appending "Internal" after a dependency property; the WPF designer can't find it, but the CLR can. Some of the solutions didn't allow multiple commands to the same control. Some of the solutions didn't allow parameters.
After experimenting for a few hours I just decided to do this:
private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
ListView lv = sender as ListView;
MyViewModel vm = this.DataContext as MyViewModel;
vm.DoSomethingCommand.Execute(lv.SelectedItem);
}
So, MVVM purists, please tell me what's wrong with this? I can still Unit test my command. This seems very practical, but seems to violate the guideline of "ZOMG... you have code in your code-behind!!!!" Please share your thoughts.
Thanks in advance.

I think the fault lies in the purity requirement. Design patterns, MVVM included, are a tool in the toolbox, not an end unto themselves. If it makes more sense to break with the purity of the model for a well-considered case (and it clearly looks like you've considered this case), then break with the model.
If that works for you, and you don't believe it's an undue maintenance burden, then I'd say that nothing is wrong with what you've done. I think that you've clearly met the burden of proof for showing that this is a reasonable solution to your problem in spite of what a pure MVVM implementation might be.
(I consider this argument similar to the arguments for multiparadigm languages. While a Pure OO approach can be applied, sometimes doing things in a more functional way is more appropriate. While a Pure Functional approach can be applied, sometimes the trade offs show that OO techniques are more than worth the while.)

I agree with you that many MVVM-Command solutions are too complicated. Personally, I use a mixed approach and define my Commands in the View rather than in the ViewModel, using methods and properties from the ViewModel.
XAML:
<Window.Resources>
<RoutedCommand x:Key="LookupAddressCommand" />
</Window.Resources>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource LookupAddressCommand}" x:Name="cmdLookupAddress" />
</Window.CommandBindings>
Code (View):
Private Sub cmdLookupAddress_CanExecute(ByVal sender As System.Object, ByVal e As System.Windows.Input.CanExecuteRoutedEventArgs) Handles cmdLookupAddress.CanExecute
e.CanExecute = myViewModel.SomeProperty OrElse (myViewModel.SomeOtherProperty = 2)
End Sub
Private Sub cmdLookupAddress_Executed(ByVal sender As System.Object, ByVal e As System.Windows.Input.ExecutedRoutedEventArgs) Handles cmdLookupAddress.Executed
myViewModel.LookupAddress()
End Sub
It's not pure MVVM, but it simple, it works, it does not need special MVVM-command-classes and it makes your code much easier to read for non-MVVM-experts (= my co-workers).

Although I prefer not to write code-behind when using the MVVM pattern, I think it's OK to do it as long as that code is purely related to the UI.
But this is not the case here : you're calling a view-model command from the code-behind, so it's not purely UI-related, and the relation between the view and the view-model command is not directly apparent in XAML.
I think you could easily do it in XAML, using attached command behavior. That way you can "bind" the MouseDoubleClick event to a command of your view-model :
<ListView ItemSource="{Binding Items}">
<local:CommandBehaviorCollection.Behaviors>
<local:BehaviorBinding Event="MouseDoubleClick" Action="{Binding DoSomething}" />
</local:CommandBehaviorCollection.Behaviors>
...
</ListView>
You can also easily access the selected item of the ListView without referring to it directly, using the ICollectionView interface :
private ICommand _doSomething;
public ICommand DoSomething
{
get
{
if (_doSomething == null)
{
_doSomething = new DelegateCommand(
() =>
{
ICollectionView view = CollectionViewSource.GetDefaultView(Items);
object selected = view.CurrentItem;
DoSomethingWithItem(selected);
});
}
return _doSomething;
}
}

I believe that the goal of having "No code in the code-behind" is exactly that, a goal to reach for - not something that you should take as an absolute dogma. There are appropriate places for code in the View - and this isn't necessarily a bad example of where or how code may be simpler than an alternative approach.
The advantage of the other approaches you list, including attached properties or attached events, is that they are reusable. When you hook up an event directly, then do what you did, it's very easy to end up duplicating that code throughout your application. By creating a single attached property or event to handle that wiring, you add some extra code in the plumbing - but it's code that is reusable for any ListView where you want double-click handling.
That being said, I tend to prefer using the more "purist" approach. Keeping all of the event handling out of the View may not effect the testing scenario (which you specifically address), but it does effect the overall designability and maintainability. By introducing code into your code behind, you're restricting your View to always using a ListView with the event handler wired - which does tie your View into code, and restrict the flexibility to redesign by a designer.

What #JP describes in the original question and #Heinzi mentions in is answer is a pragmatic approach to handling difficult commands. Using a tiny bit of event handling code in the code behind comes in especially handy when you need to do a little UI work before invoking the command.
Consider the classic case of the OpenFileDialog. It's much easier to use a click event on the button, display the dialog, and then send the results to a command on your ViewModel than to adopt any of the complicated messaging routines used by the MVVM toolkits.
In your XAML:
<Button DockPanel.Dock="Left" Click="AttachFilesClicked">Attach files</Button>
In your code behind:
private void AttachFilesClicked(object sender, System.Windows.RoutedEventArgs e)
{
// Configure open file dialog box
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".txt"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show open file dialog box
bool? result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = dlg.FileName;
// Invoke the command.
MyViewModel myViewModel = (MyViewModel)DataContext;
if (myViewModel .AttachFilesCommand.CanExecute(filename))
{
noteViewModel.AttachFilesCommand.Execute(filename);
}
}
}
Computer programming is inflexible. We programmers have to be flexible to order to deal with that.

Decoupling is one of the major feature of MVVM. If suppose you want to change say view or binded model to it. How much easy it is for your application?
Take an example where View1 and View2 both share the same ViewModel. Now will you implement the code behind method for both.
Also, suppose if you need to change the viewmodel for a view on later stage your command will get fail as view model is changed and statement
MyViewModel vm = this.DataContext as MyViewModel;
will return null and hence code crash. So there comes an extra burden to change the code behind also. These kind of scenarios will arise if you do it in this way.
Of course there are many ways to achieve the same thing in programming but which one is best will lead to best approach.

Commanding is for chumps. Real men wire up their entire ui to events in codebehind.

Related

How to bind UWP Control's Methods to a Method or Command in MVVM

I am completely new to MVVM and I am creating an UWP app for keeping track of my software development, I am still learning.
So what I want to make is:
An app that contains single page ->
In MainPage.xaml I have something like this:
<!--MainPage Content-->
<Grid>
<!--For SearchBox-->
<AutoSuggestBox x:Name="SearchBox"/>
<!--For Adding Item-->
<AppBarButton x:Name="AddAppButton"/>
<!--Listview that contains main data-->
<ListView x:Name="AppsListView"/>
<!--This is DataTemplate of listview-->
<DataTemplate>
<Grid>
<!--Icon of App-->
<Image/>
<!--Name of App-->
<TextBlock/>
<!--For Editing Item-->
<AppBarButton/>
<!--For Deleting Item-->
<AppBarButton/>
</Grid>
</DataTemplate>
</Grid>
In Model I have something like this:
public class DevApp
{
public string name { get; set; } // For App Name
public string Iconsource { get; set; } // For App Icon
public ICommand EditCommand; // For Edit AppBarButton
public ICommand DeleteCommand; // For Delete AppBarButton
}
In ViewModel, something like :
public class ViewModel
{
// For ItemSource of ListView
public ObservableCollection<DevApp> DevApps = new ObservableCollection<DevApp>();
// For Add AppBarButton
public ICommand AddCommand;
}
Now this is me first time trying to create a neat and clean Mvvm app.
Now I have this question:
I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel ?
How can I Load Data from save file ? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )
Where shall I put Data class that can manage load save and edit data to savefile.
How shall I distribute responsibilities among classes ?
I have seen people using mvvm and they create files like:
services, helpers, contracts, behaviours, etc.
and I have seen same thing in Windows Community Toolkit Sample App
Is it required for Mvvm.
And what are services and helpers.
Shall I really use Mvvm for this ?
I tried using Mvvm in this just for curiosity but like
ITS BEEN 1 MONTH I AM MAKKING THIS APP! but it gets messed up again and again,
If I used Code Behind it would have been done in few days.
BY time now I realize that Mvvm is good at data bind in complex apps but
When it comes to simple things like a simple app with listview, I think code-behind
is better and it keeps things simple.
Please answer these questions I am really struggling in making this app.
I know how to bind command to button or AppBarButton but how am I supposed to bind a Methods of a Xaml Control such as Listview's SelectionChanged() or AutoSuggestBox's TextChanged() Methods to ViewModel
You could bind SelectionChanged with command by using Xaml Behavior InvokeCommandAction, or using x:bind markup extension to bind a method, for more please refer to this link.
How can I Load Data from save file ? As there is no InitializeComponent() in ViewModel like in CodeBehind to start from, where shall I pull LoadData() method which loads data to ListView ? ( my viewmodel is bind to view using <MainPage.DataContext> and I wanna keep code behind completely empty. )
Base on the first question, you could detect Page Loaded event and Invoke CommandAction where in the ViewModel. Then loading the file in the viewmodel LoadedCommand.
<i:Interaction.Behaviors>
<ic:EventTriggerBehavior EventName="Loaded">
<ic:InvokeCommandAction Command="{x:Bind ViewModel.LoadedCommand}" />
</ic:EventTriggerBehavior>
</i:Interaction.Behaviors>
Where shall I put Data class that can manage load save and edit data to savefile
The better place that savefile is current app's local folder, and it have full access permission, please refer to Work with files document.
How shall I distribute responsibilities among classes ?
I have seen people using mvvm and they create files like:
services, helpers, contracts, behaviours, etc.
and I have seen same thing in Windows Community Toolkit Sample App Is it required for Mvvm. And what are services and helpers.
For mvvm design, model view viewmodel are necessary. And it is not necessary to make services, helpers, contracts, behaviours, it should base on your design. For example if you want to make NavigateService, you need make static service class to manager current app's navigation. We suggest you make sample project with TempleStudio that contains some base service and behaviors.
Shall I really use Mvvm for this ?
I tried using Mvvm in this just for curiosity but like
ITS BEEN 1 MONTH I AM MAKKING THIS APP! but it gets messed up again and again,
If I used Code Behind it would have been done in few days. BY time now I realize that Mvvm is good at data bind in complex apps but
When it comes to simple things like a simple app with listview, I think code-behind
is better and it keeps things simple.
Your understanding is correct, But Decoupling(mvvm) your code has many benefits, including:
Enabling an iterative, exploratory coding style. Change that is isolated is less risky and easier to experiment with.
Simplifying unit testing. Code units that are isolated from one another can be tested individually and outside of production environments.
Supporting team collaboration. Decoupled code that adheres to well-designed interfaces can be developed by separate individuals or teams, and integrated later.
Improving maintainability. Fixing bugs in decoupled code is less likely to cause regressions in other code.
In contrast with MVVM, an app with a more conventional "code-behind" structure typically uses data binding for display-only data, and responds to user input by directly handling events exposed by controls. The event handlers are implemented in code-behind files (such as MainPage.xaml.cs), and are often tightly coupled to the controls, typically containing code that manipulates the UI directly. This makes it difficult or impossible to replace a control without having to update the event handling code. With this architecture, code-behind files often accumulate code that isn't directly related to the UI, such as database-access code, which ends up being duplicated and modified for use with other pages.

Does calling View Model methods in Code Behind events break the MVVM?

I wonder if that would break the MVVM pattern and, if so, why and why is it so bad?
WPF:
<Button Click="Button_Click" />
Code Behind:
private void Button_Click(object sender, RoutedEventArgs e)
{
ViewModel.CallMethod();
}
View Model:
public void CallMethod()
{
// Some code
}
IMHO, it keeps the code behind quite simple, the view model is still agnostic about the view and code behind and a change to the view doesn't affect the business logic.
It seems to me more simple and clear than Commands or CallMethodAction.
I don't want the kind of answer "it is not how it should be done". I need a proper and logical reason of why doing so could lead to maintenance or comprehension problems.
Nope, this is perfectly fine.
It's the View's job to handle user input and interact with the ViewModel. A button click event-handler, which calls a method of the ViewModel in response, falls quite cleanly into this role.
What you have posted is clean, readable, efficient, maintainable, and fully in the spirit of the MVVM design pattern.
Now, in a more general sense, what you really want to ask is: "why choose ICommands, vs Event Handlers for MVVM?" Well, you certainly wouldn't be | the | first.
No, it doesn't break MVVM, as long as you don't introduce logic that more appropriately belongs in the viewmodel.
It has the potential to reduce the clarity, IMO, because it breaks the view into XAML and c# files that are tightly coupled and where you can't see everything going on in one place. I find it easier to have zero code behind because it means less context switching when working on the view.
It can also make it more challenging to work in an environment where your UI designer isn't a C# programmer, because then two different people are maintaining the tightly-coupled files.
Edit
Here's an example of what I mean. This is from a weekend project I did to implement Minesweeper in WPF for fun and experience. One of my biggest WPF challenges was mouse input. For anyone who hasn't wasted time on the game before, the left mouse click reveals a cell, the right mouse button toggles a flag on the cell, and the middle mouse button will (conditionally) reveal adjacent cells.
I first started by considering using System.Windows.Interactivity's EventTrigger along with InvokeCommandAction to map events to commands. This sort-of worked for the right mouse button (wasn't a true click event, but a MouseRightButtonUp) but it wouldn't work at all for the middle mouse button which had no specific actions, only the generic MouseDown/MouseUp. I briefly considered prism's variation on InvokeCommandAction which could pass the MouseButtonEventArgs to its handler, but that very much broke the MVVM concept and I quickly discarded it.
I didn't like the idea of directly putting event handlers in the code-behind because that tightly coupled the action (the mouse click) and the response (revealing cells, etc.). It also wasn't a very reusable solution - every time I wanted to handle a middle click I'd be copying, pasting, and editing.
What I settled on was this:
<i:Interaction.Triggers>
<mu:MouseTrigger MouseButton="Middle" MouseAction="Click">
<i:InvokeCommandAction Command="{Binding Path=RevealAdjacentCells}" />
</mu:MouseTrigger>
</i:Interaction.Triggers>
In this case, there's no code in the code behind. I moved it into a MouseTrigger class I created that inherits from System.Windows.Interactivity.TriggerBase which, while being view-layer code, isn't part of any specific view, but a class which any view could utilize. This handler code is as agnostic as possible as to what kind of element it's attached to - anything derived from UIElement will work.
By leveraging this approach, I gained two key things over doing this in the event handlers on the code-behind:
There's a loose coupling between the event and the action. If I had a UXD working on the UI, they could change what mouse button the command was associated to by just editing a line of XAML. For example, swapping right and middle mouse buttons is trivial and requires no .cs changes.
It's reusable on any UIElement, not tied to any particular one. I can pull this out anytime I need to solve this kind of problem in the future.
The main drawback here is that it was initially more work to set up. My MouseTrigger class is more complex than the event handlers by themselves would be (mainly around properly handling dependency properties & changes thereof). XAML can also often be rather verbose for something that would seem simple.

In WPF, a property should be changed by its name or by use of binding

I am new to WPF and a question arose in my mind while I was developing my app.
Assume that I have a textbox defined as below
<TextBox x:Name="MyTextBox" />
Then in my C# code, I can change the string shown in this textbox using the following command
MyTextBox.Text = "Hello!";
However, there is another way to have the same behavior by use of binding when in XAML we have
<TextBox x:Name="MyTextBox" Text="{Binding Content}" />
and in C# we have
public class MyText : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _content;
public string Content
{
get { return _content; }
set
{
_content = value;
PropertyChanged(this, new PropertyChangedEventArgs("Content"));
}
}
}
MyText txt = new MyText();
MyTextBox.DataContext = txt;
txt.Content = "Hello!";
Obviously the second option needs more coding, but the result of both of them are the same. However, in second case I do not have to care about executing the code on UI thread. So everywhere in my code when I change txt.Content the string in the textbox will change without any exception.
My question is: Is there any design issue preferences over any of these two options for changing a property?
The second option is a prerequisite for employing MVVM pattern.
In the first option there is no decoupling; every operation takes place in the view.
But if you prefer the section option and apply MVVM pattern, you will have two different classes; one for implementing only UI - namely View, and one for abstracting the View and the Model.
You may refer to this web page for more detail.
Depends on what type of project you are working on. If its a really small project, I believe you can use the direct assignment through code. Its the quick & dirty way of doing things. But hey... If it works.. it works. :)
If you are working on a bigger project, I'm sure you will find a lot of advantages of using bindings and the MVVM pattern. Event if you don't know MVVM you will see that using bindings will make you grow into the pattern automatically.
But hey... I believe this is a matter of opinion
You've pretty much covered all the pros and cons of each. With bindings, changes to the text in the code can be automatically updated in the UI and vice versa. As someone else said, if you want to use a view model then the 2nd option will be preferable, but unless you're required to strictly adhere to MVVM principles you can always mix and match as you see fit. That said, it can make your code confusing to yourself and others so it's best to just pick one style and stick with it.

MenuItem keyboard shortcuts in 'pure' MVVM?

All menus/contextmenus/toolbars I use in wpf are declared in ViewModel code pretty much like this:
MenuService.Add( new MenuItem()
{
Header = "DoStuff",
Command = new relayCommand( DoStuff, () => CanDoStuffExecute() )
// some more properties like parent item/image/...
} );
The MenuService provides a single binding point which is a hierarchical list of MenuItem and gets bound to the actual Menu's ItemsSource in xaml.
This works very well and now I'd like to add keyboard shortcuts in the same convenient way.
Ideally MenuItem would get a property of type System.Windows.Input.KeyGesture so I can simply write
Shortcut = new KeyGesture( Key.D, ModifierKeys.Control )
which would result in the Command of the item being called upon hitting Ctrl+D in the window that owns the menu, and which would also lead to automatically display "Ctrl+D" in the menu.
However I'm lost here: I wanted to set the MenuItem.InputBindings collection via databinding but it is get-only. How can I get items into it anyway? Or is there an MVVM framework that already supports something like this? Most q&a I found on keyboard shortcuts are all about setting the shortcuts through xaml, which is of no help.
Update
Searching for 'relaycommand vs routeduicommand and 'relaycommand keygesture' etc did reveal enough information to come up with a working though hacky solution. There are definitely other and better ways out there, but at the moment this is ultra low priority for me and does the job perfectly. I added two properties to the MenuItem class like this:
//Upon setting a Gesture, the original command is replaced with a RoutedCommand
//since that automatically gives us proper display of the keyboard shortcut.
//The RoutedCommand simply calls back into the original Command.
//It also sets the CommandBinding property, which still has to be added to the
//CommandBindingCollection of either the bound control or one of it ancestors
public InputGesture Gesture
{
set
{
var origCmd = Command;
if( origCmd == null )
return;
var routedCmd = new RoutedCommand( Header,
typeof( System.Windows.Controls.MenuItem ),
new InputGestureCollection { value } );
CommandBinding = new CommandBinding( routedCmd,
( sender, args ) => origCmd.Execute( args.Parameter ),
( sender, args ) => { args.CanExecute = origCmd.CanExecute( args.Parameter ); } );
Command = routedCmd;
}
}
//CommandBinding created when setting Gesture
public CommandBinding CommandBinding { get; private set; }
So this gives the functionality I asked for originally (ie adding keyboard shortcuts in code where they are easily configurable etc). All that is left is to register the commandbindings. At the moment this is done simply by adding all of them to Application.Current.MainWindow.CommandBindings.
This doesn't actually qualify as an 'answer' (I'm not able to add a comment evidently) - but I'd suggest that what you're doing, is not the intended method in WPF. You're doing this the Windows Forms way (and as in many other toolkits) - defining your UX in code. You got as far as you did, but now you've run into a brick wall: the key gestures are purely UX, definitely not to be specified in code-behind. The appearance (as a function of the view-model), and the user's interaction with it (ways of making a given command happen) are for the XAML definition.
Property values, and Commands are for your view-model, so that you can reuse this view-model for other views, and also easily create unit-tests for it. How would implementing your keyboard shortcuts in the view-model help the testability? And for use in other views, one could argue that the actual shortcuts might not apply to a new view, so that is not where those belong. You may have other reasons of course - but I'd suggest you might consider just defining these in XAML.
-Added, in response to your comment-
You're quite right - and I've seen some rather large WPF UX projects that tried hard to avoid any code-and wound up unnecessarily obtuse. I try to just use whichever approach yields a working result, and is as simple as I can get it.
Here is a sample snippet that simply creates the MenuItem..
<Menu x:Name="miMain" DockPanel.Dock="Top">
<MenuItem Command="{Binding Path=MyGreatCommand}" Header="DoSomething"/>
That creates the menu. Here, MyGreatCommand is an ICommand, and is simply a property on the view-model. I generally place that within a DockPanel, to handle the StatusBar, etc.
To assign the key gesture..
<Window.InputBindings>
<KeyBinding Key="X" Modifiers="ALT" Command="{Binding Path=MyGreatCommand}"/>
However, since you mentioned that you've already searched for answers and found only XAML - I assume you've already tried this approach. I have used RoutedUICommands instead of user-defined ICommands, to get that nice right-aligned key-gesture in the header text, but I haven't found how to do both. If you insist upon creating the commands and key-gestures all in code, you may have to create RoutedUICommands.
Why are you wanting to set the key-gestures in other than your XAML?
If you want some menu-items to appear only when certain states hold sway within your view-model, then you can bind the Visibility property of a menu-item (which can contain other menu-items) to Collapsed or Visible.

.Net C# Design View errors

I have subclassed a Treeview and on instantiation it loads a new ImageList (and the associated Images).
Whenever I switch to the designer view, it's also trying to run this code, however the images aren't in the designer's path, so it crashes. I ended up putting in a hack to see if the current directory is "Visual Studio", then do nothing... but that's so ugly.
I find this happening for other things. If a control is trying to use objects during load/initalization that are only available while the program is running, then the Design View cannot bring up the control.
But is there a way to get around this?
I guess what I'm hoping for is having a try/catch for the Designer (only) with the ability to ignore a few errors I know will be happening (like FileNotFoundException, etc.).
Thanks
Everything that inherits from System.Windows.Forms.Control has a DesignMode property that returns a boolean indicating if you are in design mode or not. You could use this to determine when to/when not to load external resources.
Usually it is better to move the loading of these resources to an override of OnLoad as they are rarely required directly at construction. This fixes the issue you are seeing and means that only trees which get displayed at least once will perform these additional resource loading steps.
Otherwise, you can just exclude these steps during design time by checking the DesignMode property and acting accordingly.
This is a fine pattern to use if you're making a control library with a sample of images when shown in the designer or hook ins to other designer features but as a pattern for development I'm not sure it's very effective.
I would suggest shifting your "business logic" (in this case your loading of certain images into a treeview) outside of the bounds of your treeview control. In your case I would place the logic within the Load event of the form that the control is inside:
public void Load(object sender, EventArgs e)
{
string path = "c:\somePath\toAwesome\Images";
myFunkyTreeView.AddImages(path);
}
For larger apps I personally think you want to shift the logic even out of the forms themselves, but this is debatable measure as it requires additional plumbing as a trade-off for the flexibility this provides.
Thanks for pointing me in the right directioon guys.
I had tried registering to the OnLoad event, but that event is triggered when the Design View comes up, so that didn't quite work for me (am I doing something wrong?).
Anyway, I looked a bit more into the DesignMode property. It can only work for Controls, and sometimes your object may not even be a control.
So here's the answer I prefer:
if (LicenseManager.UsageMode == LicenseUsageMode.Designtime) {
// design-time stuff
} else {
// run-time stuff
}
Found it here.

Categories