tags:

views:

317

answers:

3

I have followed the Accepted Answer's instructions from this post as regards creating a code behind file for a Resource Dictionary, and it worked...so now I can attach events to controls in the generic.xml file.

But now I want to be able to call the DragMove() method from an event in there and since there aren't any references to the window hosting the dictionary at the time, I don't know how to call this DragMove() method.

So, from a Resource Dictionary Code behind file, is there any way I can make a reference to the window that will currently be hosting that Resource Dictionary?


[Update] (Temporary Solution)

As a simple (yet stupid) workaround, I have currently done the following:
Since I can reference the Application.Current.MainWindow from the Generic.xaml.cs code-behind, I now have this in the Generic.xaml.cs:

private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{               
    Application.Current.MainWindow.DragMove();
}

And then I'm attaching PreviewMouseLeftButtonDown handler to each Window I have, like such:

private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Application.Current.MainWindow = this;
}

It, well, it works...and until someone can come up with the proper way on how to do this, It should serve me well enough.

A: 

You can access your main window through

Application.Current.MainWindow

Hope this helps

Arcturus
That's not the current window, that's the main window. They are often not the same thing.
Kent Boogaart
+2  A: 

There is no way I know of doing this. However, if you're trying to determine the Window given a specific resource, you could use a RelativeSource:

<SolidColorBrush x:Key="MyBrush" Color="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Converter={StaticResource WindowToColorConverter}"/>

And if you're doing it from code, you can use Window.GetWindow(). You just need a DependencyObject hosted in that Window.

HTH, Kent

Kent Boogaart
A: 

From architectural point of view I would say you are about to break the paradigm. It might be a bad decision providing Resource Dictionary with notion of UI that consumes it and giving some logic other than providing resources.

You might want some Adapter between UI and resource dictionary, or Controller if this is really needed to wire Resource Dictionary but again you shouldn't inject any logic in a resource container...

Denis Vuyka