問題描述
我瀏覽了這個網(wǎng)站和谷歌,但這些解決方案對我不起作用.
I looked over this web and google and the solutions didn't work for me.
我在 UserControl 的 ViewModel 上有一個命令.好吧,用戶控件有一個綁定到 ObservableCollection 的 ItemsControl.在 ItemsControl.ItemTemplate 的 DataTemplate 中,我有一個按鈕,我想使用該命令.我無法綁定命令,因為在 DataTemplate 內(nèi)部,數(shù)據(jù)上下文不是 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.
問題是:如果丟失了父數(shù)據(jù)上下文,我如何將按鈕綁定到命令?
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 內(nèi)為集合中的每個元素使用了一個數(shù)據(jù)模板.好吧,您想刪除所選項目,并在該作業(yè)的每一行中放置一個按鈕.?你是怎么做到的?
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;
簡而言之.您將行(所選項目)的數(shù)據(jù)上下文發(fā)送給演示者.
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).
如您所見,按鈕必須存在于數(shù)據(jù)模板中,然后數(shù)據(jù)上下文不再是 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 事件.在事件處理程序中,調(diào)用 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.
這篇關(guān)于使用父級的 DataContext(WPF - 動態(tài)菜單命令綁定)的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!