如何通过单击绑定到WPF中列表视图控件的上下文菜单来获取所选项目?
这是我的标记:
<ListView Name="lvCustomerJobs">
<ListView.ContextMenu>
<ContextMenu>
<MenuItem Header="Remove"
Click="cmCustomerRemoveJob"
Command="{Binding RemoveItem}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu},
Path=PlacementTarget.SelectedItem}" />
</ContextMenu>
</ListView.ContextMenu>
<ListView.View>
<GridView>
<GridViewColumn Header="Status" Width="150" DisplayMemberBinding="{Binding Status}" />
<GridViewColumn Header="Booked in by" Width="150" DisplayMemberBinding="{Binding BookedInBy}" />
<GridViewColumn Header="Date Required" Width="150" DisplayMemberBinding="{Binding DateRequired}" />
</GridView>
</ListView.View>
</ListView>
这是我背后的代码:
private void cmCustomerRemoveJob(object sender, RoutedEventArgs e)
{
var item = ((FrameworkElement)e.OriginalSource).DataContext as User;
if (item != null)
{
MessageBox.Show(item.DateRequired + " Item's Double Click handled!");
}
}
但是项目是否为空?
答案 0 :(得分:1)
您应该将sender
对象投射到MenuItem
,然后像这样使用CommandParameter
:
private void cmCustomerRemoveJob(object sender, RoutedEventArgs e)
{
var item = ((MenuItem)sender).CommandParameter as User;
if (item != null)
{
MessageBox.Show(item.DateRequired + " Item's Double Click handled!");
}
}
答案 1 :(得分:0)
我将ListView绑定到模型中的集合,并将SelectedItem绑定到模型。
<ListView ItemSource="{Binding CustomerCollection}" SelectedItem="{Binding SelectedCustomer}">
然后,我的命令方法可以根据需要引用SelectedCustomer。
如果出于某种原因这不理想,我很想知道!