使用父母的DataContext(WPF - 动态菜单命令绑定) [英] Using the parent's DataContext (WPF - Dynamic Menu Command Binding)

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

问题描述

我看了看这个网站和谷歌的解决方案并没有为我工作。

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

我有一个用户控件的视图模型的命令。那么,在用户控件有绑定到的ObservableCollection一个ItemsControl的。该ItemsControl.ItemTemplate的DataTemplate中里面我有一个按钮,我想使用的命令。 。因为里面的DataTemplate,在DataContext不是视图模型,但的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.

现在的问题是:我怎样才能绑定按钮该命令,如果失去了父母的DataContext?

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.

想象一下sceneario:

Imagine this sceneario:

您有一个ObservableCollection的ItemsSource的一个ListBox的项目,所以你正在使用的列表框里面一个DataTemplate对于集合中的每个元素。好吧,你要删除选定的项目,你把一个按钮,每一行中该作业。 ?¿你怎么做了。

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;

在做空。您发送行(所选项目),以演示的DataContext的。

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

但是,我怎么能做到这一点的方式MVVM?因为我需要使用一个命令,但我不能命令分配到按钮,因为此按钮也一无所知视图模型(其中安装了该命令)。

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).

由于你可以看到,该按钮具有的DataTemplate里面存在,那么在DataContext不是视图模型了....还有就是为什么我需要访问父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破的解决方案,然后设置标签=按钮{}绑定并处理Click事件。在事件处理程序,调用命令你的视图模型。

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 - 动态菜单命令绑定)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆