Mise à jour pour essayer d'aider Greg à partir des commentaires. La commande fonctionne dans le menu principal de Windows, le bouton dans le contrôle utilisateur et le menu contextuel dans le contrôle utilisateur.
Je le ferais avec des commandes. Donc, avoir une classe Commands.cs quelque chose comme:
public static class Commands
{
public static RoutedUICommand TestShowDialogCommand = new RoutedUICommand("Test command", "TestShowDialog", typeof(Commands));
}
enregistrer ces dans la fenêtre principale: (vous n'avez pas besoin canshow valeur par défaut true)
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;
}
Ceci est mon XAML pour la fenêtre principale:
<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">
<Grid>
<StackPanel>
<Menu>
<MenuItem Header="Test">
<MenuItem Header="ShowDialog" Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}"/>
</MenuItem>
</Menu>
<WpfApplication1:BazUserControl />
</StackPanel>
</Grid>
</Window>
C'est le XAML pour mon contrôle utilisateur (code par défaut derrière seulement)
<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">
<Grid>
<StackPanel>
<Button Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}" Content="ClickMe" ></Button>
<TextBox>
<TextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="ShowDialog" Command="{x:Static WpfApplication1:Commands.TestShowDialogCommand}" />
</ContextMenu>
</TextBox.ContextMenu>
</TextBox>
</StackPanel>
</Grid>
</UserControl>
Vous pourriez aller un peu plus loin et gérer la commande dans une classe de contrôleur à la place et rendre ce bit plus MVC.
Une réponse correcte et acceptable a probablement déjà été envoyée. Basé uniquement sur les votes, Martin devrait probablement être accepté. – Emyr