列表框项目上下文菜单WPF和MVVM

时间:2017-05-03 15:42:50

标签: c# wpf xaml mvvm listbox

我尝试过很多解决方案,但不适用于我。 我正在使用WPF和MVVM。

我有以下XAML文件

<UserControl x:Class="MyApp.View.AvailableItems"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyApp.View"
             xmlns:presenter="clr-namespace:MyApp.ViewModel.Presenter"
             mc:Ignorable="d" 
             d:DataContext="{d:DesignInstance presenter:MainPresenter}"
             d:DesignHeight="300" d:DesignWidth="300">

    <DockPanel Margin="10">
        <Label DockPanel.Dock="Top">Available Items</Label>
        <ListBox ItemsSource="{Binding ItemsList}" SelectedItem="{Binding SelectedListItem}">
            <ListBox.ContextMenu>
                <ContextMenu DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
                    <MenuItem Header="Delete" Command="{Binding Path=DataContext.RemoveSelectedItem}" 
                              CommandParameter="{Binding SelectedListItem}" />
                </ContextMenu>
            </ListBox.ContextMenu>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}"
                                   FontWeight="Bold" Foreground="Blue"/>

                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DockPanel>
</UserControl>

我有MainPresenter

   private ItemModel _selectedItem;
   public ItemModel SelectedListItem
   {
            get => _selectedItem;  
            set
            {
                if (Equals(_selectedItem, value)) return;
                _selectedItem= value;
                RaisePropertyChangedEvent("SelectedListItem");
            }
        }
    public IEnumerable<ItemModel > ItemsList=> _dataStore.GetItems();
    public ICommand RemoveSelectedItem()
    {
       return  new RelayCommand<ItemModel>(RemoveSelectedItemFromList);
    }
    private void RemoveSelectedItemFromList(ItemModel item)
    {
            MessageDialogs.ShowInfoMessage(item.Name);
     }

列表工作正常,添加和删除项目。 SO绑定有效,但是当我从上下文菜单中单击Delete时,没有任何反应。 可能有什么不对,我几乎尝试了一切。我想问题是DataContext,但是如何修复呢?

1 个答案:

答案 0 :(得分:0)

问题在于你的约束力。

public ICommand RemoveSelectedItem()
{
   return  new RelayCommand<ItemModel>(RemoveSelectedItemFromList);
}
private void RemoveSelectedItemFromList(ItemModel item)
{
   MessageDialogs.ShowInfoMessage(item.Name);
}

您无法对方法应用Binding。您只能将其应用于公共属性。因此,您的ICommand绑定应该是

private readonly ICommand _rsi = = new RelayCommand<ItemModel>(RemoveSelectedItemFromList);
public ICommand RemoveSelectedItem { get { return _rsi; } }