我不知道如何使标题中的'问题'(不同行为)更清晰,但我会在这里解释。WPF MenuItem vs当鼠标仍然关闭时,新窗口中的按钮行为
在我们的WPF应用程序中,我们使用DataGrid控件列出了一些实体。双击一行后,我们打开一个新窗口,在该窗口中,还有一些MenuItem控件。
问题是,当窗口打开时,其中一个菜单项位于鼠标指针正下方的位置,实际上在双击鼠标上单击该菜单项。
当我们使用按钮代替时,按钮点击事件不会在相同的情况下自动触发。
我们现在考虑使用按钮而不是菜单项(或创建自定义菜单),但也许这里有人有解释或解决方案来改变这种行为?就我个人而言,我想不出一个这样会有利的情况。提前致谢!
示例代码如下。为了明白我的意思,双击DataGrid行打开新窗口并按住鼠标按钮,移动到菜单项并让鼠标按钮放开(在TestWindow.xaml中,交换MenuItem作为Button控件以查看在行为上的差异):
MainWindow.xaml
<Window x:Class="WpfApplication2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="DataGridRowStyle"
TargetType="{x:Type DataGridRow}">
<EventSetter Event="MouseDoubleClick" Handler="DataGridRow_MouseDoubleClick" />
</Style>
</Window.Resources>
<DataGrid RowStyle="{StaticResource DataGridRowStyle}" x:Name="MyDataGrid">
<DataGrid.Columns>
<DataGridTextColumn Header="String" Binding="{Binding}" IsReadOnly="True" />
</DataGrid.Columns>
</DataGrid>
MainWindow.xaml.cs
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
ObservableCollection<string> myCollection = new ObservableCollection<string>();
myCollection.Add("test");
MyDataGrid.ItemsSource = myCollection;
this.DataContext = this;
}
private void DataGridRow_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
TestWindow window = new TestWindow();
window.Show();
window.Activate();
}
}
TestWindow.xaml
<Window x:Class="WpfApplication2.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300">
<Grid>
<MenuItem Header="Test" Click="Button_Click" />
</Grid>
TestWindow.xaml.cs
public partial class TestWindow : Window
{
public TestWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
感谢您的答案,但它不起作用。不是最好的解决方案,如果它可以工作,但是再一次,它似乎是一个很好的解决方案可能不存在。 ;) – 2010-07-28 06:51:51