WPF Extending Window
So I have a bunch of WPF Windows in my Windows Application. I want each window to have a context menu that has one item ( see the code bellow ). However, I don't feel like copying and 开发者_开发知识库pasting this code everywhere. I would like to somehow extend the WPF Window class ( and call it PrintableWindow ) and somehow make every window be an extension of the PrintableWindow ....Is this possible ???
<Window.ContextMenu>
<ContextMenu>
<ContextMenu.Items>
<MenuItem Header="Print"
Click="mnuPrint_Click">
</MenuItem>
</ContextMenu.Items>
</ContextMenu>
</Window.ContextMenu>
You shouldn't need to extend window to do accomplish this, just created a global style for all windows.
In your app.xaml file:
<Style TargetType="{x:Type Window}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<ContextMenu.Items>
<MenuItem Header="Print" Command="Print" />
</ContextMenu.Items>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
You will have to create a handler for the print command in the window if you want to print from a particular window. Even better, if you are using a view model you can just bind to your command.
Create your own Window
class called PrintableWindow
which derives from
Window
and then modify any other Window
instances to derive from your PrintableWindow
versus Window
. This way all Window
instances will be of type PrintableWindow
which has your ContextMenu
and handler associated with it.
精彩评论