[英]How to create a ContextMenu when the mouse button is pressed
I made a code for a DataGrid that fire the right mouse button event, in particular: 我为DataGrid编写了一个代码,该代码触发了鼠标右键事件,尤其是:
private void Squadre_DataGrid_MouseClick(object sender, MouseEventArgs e)
{
if (e.RightButton == MouseButtonState.Pressed)
{
//Context menu
}
}
I want create a ContextMenu inside the condition, and associate for each item of the ContextMenu a method that will be executed if the item will be choose. 我想在条件内创建一个ContextMenu,并为ContextMenu的每个项目关联一个将被选择的方法,该方法将被执行。 How to do this? 这个怎么做?
Perhaps you can achieve that in XAML. 也许您可以在XAML中实现这一目标。 Assuming you want to have a context menu for the rows of your DataGrid, you can add the ContextMenu property to your DataGridRow, for example: 假设要为DataGrid的行提供一个上下文菜单,可以将ContextMenu属性添加到DataGridRow中,例如:
<DataGrid>
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="ContextMenu" Value="{StaticResource theContextMenu}" />
</Style>
</DataGrid.RowStyle>
</DataGrid>
Then add the context menu itself in the resource dictionary: 然后将上下文菜单本身添加到资源字典中:
<Window.Resources>
<ResourceDictionary>
<ContextMenu x:Key="theContextMenu">
<MenuItem Header="Menu Item 1" Click="menuItem1_Click">
</MenuItem>
<MenuItem Header="Menu Item 2" Click="menuItem2_Click">
</MenuItem>
</ContextMenu>
</ResourceDictionary>
</Window.Resources>
Then write a click event handler for each menu item to execute your method: 然后为每个菜单项编写一个click事件处理程序以执行您的方法:
private void menuItem1_Click(object sender, RoutedEventArgs e)
{
// execute your method..
}
private void menuItem2_Click(object sender, RoutedEventArgs e)
{
// execute your method..
}
You could bind datacontext content to a propertie and than fill It (propertie) in your Button event. 您可以将数据上下文内容绑定到属性,然后在Button事件中填充它(属性)。 Don't forget to set Update condition in Contextmenu binding (xaml) 不要忘记在Contextmenu绑定(xaml)中设置更新条件
In my view the best form of work this out is adding an ContextMenu
for each row of DataGrid
, we can do it in the following way: 在我看来,最好的工作方式是为DataGrid
每一行添加一个ContextMenu
,我们可以通过以下方式实现:
In the XAML
, place in your DataGrid
an listener to event LoadingRow
: 在XAML
,在DataGrid
放置事件LoadingRow
的侦听LoadingRow
:
<!-- resume version of declaration your DataGrid -->
<DataGrid x:Name="Squadre_DataGrid" LoadingRow="Squadre_DataGrid_LoadingRow" />
In the CodeBehind
, come on add the ContextMenu
for each row: 在CodeBehind
,为每行添加ContextMenu
:
private void Squadre_DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
ContextMenu _contextMenu = new ContextMenu();
MenuItem mia = new MenuItem();//item 1
MenuItem mib = new MenuItem();//item 2
....
_contextMenu.Add(mia);
_contextMenu.Add(mib);
....
e.Row.ContextMenu = _contextMenu;//add context menu to row
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.