Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Updating to try and help Greg from the comments. The command works in the main windows menu, the button in the user control and the context menu in the user control.</p> <p>I'd do it with commands. So have a class Commands.cs something like:</p> <pre><code>public static class Commands { public static RoutedUICommand TestShowDialogCommand = new RoutedUICommand("Test command", "TestShowDialog", typeof(Commands)); } </code></pre> <p>Register these in your main window: (you don't need the canshow it defaults to true)</p> <pre><code> public Window1() { InitializeComponent(); CommandManager.RegisterClassCommandBinding(typeof(System.Windows.Controls.Control), new CommandBinding(Commands.TestShowDialogCommand, ShowDialogCommand, CanShowDialogCommand)); } private void ShowDialogCommand(object sender, ExecutedRoutedEventArgs e) { var box = new Window(); box.Owner = this; box.ShowDialog(); } private void CanShowDialogCommand(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = true; } </code></pre> <p>This is my xaml for the main window:</p> <pre><code>&lt;Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Title="Window1" Height="300" Width="322"&gt; &lt;Grid&gt; &lt;StackPanel&gt; &lt;Menu&gt; &lt;MenuItem Header="Test"&gt; &lt;MenuItem Header="ShowDialog" Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}"/&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;WpfApplication1:BazUserControl /&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>This is the xaml for my user control (default code behind only)</p> <pre><code>&lt;UserControl x:Class="WpfApplication1.BazUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WpfApplication1="clr-namespace:WpfApplication1" Height="300" Width="300"&gt; &lt;Grid&gt; &lt;StackPanel&gt; &lt;Button Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}" Content="ClickMe" &gt;&lt;/Button&gt; &lt;TextBox&gt; &lt;TextBox.ContextMenu&gt; &lt;ContextMenu&gt; &lt;MenuItem Header="ShowDialog" Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}" /&gt; &lt;/ContextMenu&gt; &lt;/TextBox.ContextMenu&gt; &lt;/TextBox&gt; &lt;/StackPanel&gt; &lt;/Grid&gt; &lt;/UserControl&gt; </code></pre> <p>You could take it a bit further and handle the command in a controller class instead and make it that bit more MVC.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload