在我的应用程序中,我有一个视图(ListView)和一个视图模型。在视图模型内部,我有两个属性:第一个是项目列表,第二个是命令。我想在ListView中显示来自第一个属性的项目。此外,我希望为每个项目都有一个上下文菜单,单击它将激活第二个属性的命令。
以下是我的视图模型代码:
现在是XAML部分:
问题:直到我实际打开上下文菜单,上下文菜单的PlacementTarget为null。在命令的“CanExecute”被调用之前,我需要以某种方式将所单击的ListViewItem的数据上下文接收到 - 我真的希望所有内容都在XAML中完成,而不需要处理任何代码后台回调。
提前感谢您。
以下是我的视图模型代码:
public class ViewModel
{
public IEnumerable Items
{
get
{
return ...; //returns a collection of items
}
}
public ICommand MyCommand //this is a command, I want to be able execute from context menu of each item
{
get
{
return new DelegateCommand(new Action<object>(delegate(object parameter)
{
//here code of the execution
}
), new Predicate<object>(delegate(object parameter)
{
//here code of "can execute"
}));
}
}
现在是XAML部分:
<ListView ItemsSource="{Binding Items}">
<ListView.Resources>
<commanding:CommandReference x:Key="myCommand" Command="{Binding MyCommand}"/>
</ListView.Resources>
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock
Text="{Binding Name}"
/>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem
Header="Remove from workspace"
Command="{StaticResource myCommand}"
CommandParameter="HERE I WANT TO PASS THE DATA CONTEXT OF THE ListViewItem"
/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</ListView.ItemContainerStyle>
</ListView>
问题:直到我实际打开上下文菜单,上下文菜单的PlacementTarget为null。在命令的“CanExecute”被调用之前,我需要以某种方式将所单击的ListViewItem的数据上下文接收到 - 我真的希望所有内容都在XAML中完成,而不需要处理任何代码后台回调。
提前感谢您。