If you run into a scenario where you need to use a WPF behavior and you want to inject it right into your XAML, you may have some difficulty. I have no explanation as to why the designer can’t load when I add a behavior to my Grid, but it happened and I lived with it for the longest time.
I have a behavior that I am attaching to a grid to make it draggable across the screen. See the first part of the behavior definition here:
Fairly standard stuff. This utilizes some of the framework found in the Microsoft Expression Blend Interactions Assembly. So we add all the necessary references and namespaces to our XAML then go ahead and add the behavior to our Grid. See it done in the following picture.
This breaks our designer! The application runs fine and the behavior works as expected, however the designer tells us “The type ‘local:DragBehavior’ was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.” This is not the end of the world, but we can no longer visualize our XAML as we write it. My solution was to comment out the behavior to make the changes necessary then uncomment it again before I debugged. That was annoying.
We don’t need the behavior during design time so why not just add it in the code behind in our constructor? I’m the developer and I’m making the UI, so why not…
To attach a WPF behavior to a UIElement in the code behind you need to utilize the Windows Interactivity assembly. Just make the following call (legendBezel is the name of my WPF Grid – DragBehavior is the class I defined for the behavior):
And finally now we can see our designer again: