为数据网格行创建上下文菜单
我有一个可能有很多行的数据网格。当用户右键单击其中一行时,我需要为每一行显示一个上下文菜单,并在用户单击该选项时执行一个操作(相同的操作,但根据当前选定的行不同的数据项)。
对此最好的策略是什么?
我担心每一行的 ContextMenu 都太过分了,即使我使用 ContextMenuOpening 事件创建菜单,有点像上下文菜单的“延迟加载”。我应该只为数据网格使用一个上下文菜单吗?但这样我就可以对点击事件进行更多的工作,以确定正确的行等。
I have a datagrid that potentially can have many rows. As the user right clicks one of the rows, I need to show a context menu for each of the rows and perform an action (same action but different data item according to the current selected row) when the user clicks the option.
What is the best strategy for this?
I'm fearing that a ContextMenu for each row is overkill even though I'm creating the menu using the ContextMenuOpening event, sort of a "lazy load" for the context menu. Should I only use one ContextMenu for the datagrid? But with this I would have some more work regarding the click event, to determine the correct row, etc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我所知,某些操作将根据行被禁用或启用,因此对于
DataGrid
来说单个ContextMenu
是没有意义的。我有一个行级上下文菜单的示例。
DataGrid
必须使用命令绑定到一系列视图模型:上下文菜单是在
UserControl
的资源集合中创建的,我认为只有一个对象可以通过引用而不是值与数据网格行连接。这是
MainViewModel
内Command
的ContextMenu
的另一个示例。我认为DataGrid
具有与DataContext
相同的正确视图模型,并且 CommandParameter 属性必须放置在 Command 属性之前:Models:
但是有一个问题
如果
不会显示为禁用项。可能的解决方法是在CanExecute
返回 false,则 MenuItemItemModel
内使用ParentModel
属性,但它与第一个解决方案没有太大区别。下面是上述解决方案的示例:
XAML 中的 MenuItem 会更简单:
As far as I know, some of the actions will be disabled or enabled depending on the row, so there is no point in a single
ContextMenu
for aDataGrid
.I have an example of the row-level context menu.
The
DataGrid
must have a binding to a list of view models with commands:The context menu is created in the resources collection of the
UserControl
and I think there is only one object which is connected with datagrid rows by reference, not by value.Here is another example of
ContextMenu
for aCommand
inside aMainViewModel
. I suppose thatDataGrid
has a correct view model as theDataContext
, also the CommandParameter attribute must be placed before the Command attribute:Models:
But there is a problem that
MenuItem
isn't displayed as a disabled item ifCanExecute
returns false. The possible workaround is using aParentModel
property inside theItemModel
, but it doesn't differ much from the first solution.Here is example of above-described solution:
And MenuItem in XAML will be simplier: