【发布时间】:2014-09-12 14:23:54
【问题描述】:
我有一个带有一些选项的上下文菜单。其中一个选项是 Observable 集合,我在将视图模型中的命令绑定到它们时遇到问题。我已经看到了许多不同的方法来解决这个问题,但没有一个有效,因为它们与我的问题没有具体关系。这是我的代码:
XAML:
<ListView ItemsSource="{Binding ListViewItems}" SelectionMode="Single">
<ListView.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Test" Command="{Binding TestCommand}" CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=PlacementTarget.SelectedItem}" />
<Separator></Separator>
<MenuItem Header="Status" ItemsSource="{Binding DataContext.ObservableCollectionList}" DisplayMemberPath="Name" Command="{Binding Path=DataContext.UpdateCommand}" CommandParameter="{Binding Path=SelectedItem}"/>
</ContextMenu>
</ListView.ContextMenu>
//listviewstuff here
</ListView>
虚拟机:
public class VM : ViewModelBase
{
public RelayCommand UpdateCommand { get; private set; }
public Action UpdateCommandAction { get; set; }
public ObservableCollection<Status> ObservableCollectionList { get; set; }
public VM()
{
this.UpdateCommand = new RelayCommand(new Action(() => this.UpdateCommandAction.DynamicInvoke())));
}
}
XAML 视图的代码隐藏:
public partial class View
{
public View()
{
InitializeComponent();
var ViewDataContext = this.DataContext as VM;
ViewDataContext .UpdateCommandAction = UpdateStatus;
}
private void UpdateStatus()
{
MessageBox.Show("test");
}
}
我插入了一个断点,它甚至没有进入方法调用。当我运行程序时,调试输出也没有显示错误。我不明白的是,当我将此命令添加到未由数据绑定列表填充的常规菜单项时,它工作正常。我希望能有一双新的眼睛,并对其工作原理有所了解。
【问题讨论】:
-
(你的视图模型中真的有一个名为
DataContext的属性吗?如果是这样,那真的很混乱,我会避免它)
标签: wpf xaml mvvm data-binding mvvm-light