tags:

views:

1711

answers:

3

Hi all,

I'm working on a wpf application, and up until recently, I had a ResourceDictionary inside my main window's resources part of the xaml. The resource dictionary contained an DataTemplate that was used to style several listboxes in the window. The xaml for this datatemplate contained pointers to event handlers, eg:

<Button n:Name="btnClickMe" Content="Click Me!" LeftMouseButtonUp="btnClickMe_Click" />

I recently decided to split the content of the window up into separate user controls, and to move my ResourceDictionary into it's own file. But, of course, there isn't a code-behind file for a resource dictionary file. How can I wire this up, with things split up as I've described?

Thanks in advance!

+1  A: 

You can add a code-behind to a ResourceDictionary; just make sure your class names are referenced correctly. For instance, in the ResourceDictionary if you were working with AppStyles.xaml the XAML file would have a class of:

x:Class="Client.App.Shell.themes.AppStyles"

In the code-behind, AppStyles.xaml.cs, you would make sure to have the class:

namespace Client.App.Shell.themes
{
    public partial class AppStyles
    ...
Jeff Wain
And don't forget to call InitializeComponent from the constructor of the code-behind class -- as far as I know there's no built-in way to get VS to do this for you!
itowlson
Actually, in the implementation I have in my current application, it doesn't require InitializeComponent() for some reason. I'd guess it's because it's not actually compiling any visuals, just acting as the dictionary, but I'm not 100% sure.
Jeff Wain
Maybe it's because we're using this technique for friendly dictionary merging, i.e. being able to write <local:AppStyles /> rather than <ResourceDictionary Source="pack://,,,component/AppStyles.xaml" /> or whatever the incantation is *grin*. If you use the latter syntax then I'm sure you're right, InitializeComponent probably isn't required. Sorry for any confusion!
itowlson
That would make sense, I might look at setting that up...
Jeff Wain
A: 

You should consider using RoutedCommands, I am thinking. there are many many resources online, here are a couple that might help you.

http://msdn.microsoft.com/en-us/library/ms752308.aspx http://www.devx.com/DevX/Article/37893/0/page/1

Muad'Dib
A: 

You can add a new class and name it with the same name as your resource dictionary plus the .cs extension and Visual Studio will automatically set things up so it becomes the code behind file.

For example if you have a resource dictionary called Buttons.xaml, add a file called Buttons.xaml.cs.

Anthony Brien