使用父级的 DataContext(WPF - 动态菜单命令绑定)

时间:2022-11-23
本文介绍了使用父级的 DataContext(WPF - 动态菜单命令绑定)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了这个网站和谷歌,但这些解决方案对我不起作用.

I looked over this web and google and the solutions didn't work for me.

我在 UserControl 的 ViewModel 上有一个命令.好吧,用户控件有一个绑定到 ObservableCollection 的 ItemsControl.在 ItemsControl.ItemTemplate 的 DataTemplate 中,我有一个按钮,我想使用该命令.我无法绑定命令,因为在 DataTemplate 内部,数据上下文不是 ViewModel,而是 ObservableCollection 的一个项目.

I have a command on the ViewModel of a UserControl. Well, The usercontrol have a ItemsControl binded to a ObservableCollection. Inside the DataTemplate of the ItemsControl.ItemTemplate I have a button and I want to use the command. I can't bind the command because inside the DataTemplate, the datacontext is not the ViewModel but an item of the ObservableCollection.

问题是:如果丢失了父数据上下文,我如何将按钮绑定到命令?

The question is: How can I bind the button to the command if a lost the parent datacontext?

我认为这需要一个简单的解决方案,因为我认为这是一个常见问题.

I think that this need to have an easy solution because I think that this is a common problem.

想象一下这个场景:

您有一个以 observableCollection 作为 ItemsSource 的 ListBox 项目,因此您在 ListBox 内为集合中的每个元素使用了一个数据模板.好吧,您想删除所选项目,并在该作业的每一行中放置一个按钮.¿你是怎么做到的?

You have a ListBox item with an observableCollection as the ItemsSource, so you are using a datatemplate inside the ListBox for every element in the collection. Well, you want to delete the selected item and you put a button in every row for that job. ¿How do you do that?

在MVP中,我可以在按钮的点击事件中做到这一点:

In MVP, I can do this in the click event of the button:

Button but = e.Source as Button;

if (but != null)
      Presenter.ActualNote = but.DataContext as Note;

简而言之.您将行(所选项目)的数据上下文发送给演示者.

In short. You send the datacontext of the row (the selected item) to the presenter.

但是,我怎样才能以 mvvm 的方式做到这一点?因为我需要使用命令但我无法将命令分配给按钮,因为按钮对 ViewModel(命令所在的位置)一无所知.

But, how can I do it in the mvvm way? Because I need to use a command but I can't assign the command to the button because the button does know nothing about the ViewModel (where the command exists).

如您所见,按钮必须存在于数据模板中,然后数据上下文不再是 ViewModel ......这就是为什么我需要访问父级的 DataContext,以访问命令.

As you can see, the button has to exist inside the datatemplate, then the datacontext is not the ViewModel anymore.... There is why I need to access to the parent's DataContext, for access to the command.

我希望你能更好地理解我的问题.

I hope that you understand my problem better.

谢谢.

推荐答案

如果你想要一个肮脏的、破坏 MVVM 的解决方案,那么在按钮上设置 Tag="{Binding}" 并处理 Click 事件.在事件处理程序中,调用 ViewModel 上的命令.

If you want a dirty, MVVM-breaking solution, then set the Tag="{Binding}" on the button and handle the Click event. In the event handler, call the command on your ViewModel.

这篇关于使用父级的 DataContext(WPF - 动态菜单命令绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

上一篇:如何在 C# 中实现具有子菜单的控制台菜单 下一篇:ASP.NET MenuItem 个人样式

相关文章

最新文章