出现的问题
xaml代码:
<Window.DataContext>
<vm:MainWindowViewModel/>
</Window.DataContext>
<ListView x:Name="ImageList"
Grid.Column="0" Grid.Row="1"
MinHeight="470"
ItemsSource="{Binding Images}"
SelectedItem="{Binding SelectedImage, Mode=OneWayToSource}" Margin="0,27,0,-16.667" Height="470" Grid.RowSpan="2" VerticalAlignment="Top" Background="#FFF0F0F0"
>
<ListView.ItemTemplate >
<DataTemplate >
<Border BorderThickness="1" BorderBrush="AliceBlue">
<Image Width="{Binding ActualWidth, ElementName=textBlock, Mode=OneWay}" Source="{Binding}" Stretch="UniformToFill">
<Image.ContextMenu>
<ContextMenu>
<MenuItem Header="删除"
Command="{Binding DeleteCommand}"/>
</ContextMenu>
</Image.ContextMenu>
</Image>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
部分ViewModel代码:
private BitmapImage _selectedImage;
private BitmapImage _image;
private ObservableCollection<BitmapImage> _images;
public BitmapImage Image
{
get
{
return _image;
}
set
{
_image = value;
base.OnPropertyChanged("Image");
}
}
public ObservableCollection<BitmapImage> Images
{
get
{
return _images;
}
set
{
_images = value;
base.OnPropertyChanged("Images");
}
}
public BitmapImage SelectedImage
{
get
{
return _selectedImage;
}
set
{
_selectedImage = value;
base.OnPropertyChanged("SelectedImage");
}
}
public ICommand DeleteCommand
{
get
{
if (_deleteCommand == null)
{
_deleteCommand = new RelayCommand(param => this.DeleteFile());
}
return _deleteCommand;
}
}
private void DeleteFile()
{
_images.Remove(_selectedImage);
base.OnPropertyChanged("Images");
}
问题说明:将ListView的suorce设置为Images,将图片显示在列表中,想要给显示的图片添加一个ContextMenu,使右击图片时,执行删除命令,移除这一张图片,但是上述的方法没反应。
解决方法:
https://stackoverflow.com/questions/25205640/wpf-binding-command-to-contextmenu
<Image Tag="{Binding DataContext,ElementName=ImageList}" Width="{Binding ActualWidth, ElementName=textBlock, Mode=OneWay}" Source="{Binding}" Stretch="UniformToFill">
<Image.ContextMenu>
<ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Header="删除"
Command="{Binding DeleteCommand}"/>
</ContextMenu>
</Image.ContextMenu>
</Image>