簡體   English   中英

列表框項目上下文菜單WPF和MVVM

[英]Listbox item Context Menu WPF and MVVM

我嘗試了很多解決方案,但沒有一個對我有用。 我正在使用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,但是如何解決呢?

問題在於您要綁定的內容。

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; } } 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM