我有一个带有ListView的应用程序,我在其中填充了图像名称,权重等,并且其中一个单元格内应有2个按钮或用于用户交互的标签。我已经搜索并尝试了在网上找到的内容,但没有任何帮助。
<StackPanel Orientation="Horizontal">
<Grid>
<Button
Grid.Row="0"
Command="{Binding ShowImageCommand}"
Content="Show">
</Button>
</Grid>
<Grid>
<Button Content="Annotate"
CommandParameter="{Binding}"
Command="{Binding DataContext.ShowImageCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MainWindow}}}" />
</Grid>
注解按钮或显示均无效。我试图像标签一样做,但也没有成功。
<Label Content="Show" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDown" >
<i:InvokeCommandAction Command="{Binding ShowImageCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>
这是在课堂上的样子:
public MainViewModel()
{
ShowImageCommand = new RelayCommand(ShowImageMethod);
}
public ICommand ShowImageCommand { get; set; }
public void ShowImageMethod()
{
RaisePropertyChanged("ShowImageCommand");
Messenger.Default.Send<NotificationMessage>(new NotificationMessage("It's fine"));
}
我是C#和MVVM模式的新手,所以大多数情况下,我只是从Stack复制粘贴代码并尝试使其正常工作。网格上的其他按钮(例如,用于将图像添加到ListView的按钮)的实现方式相同,但所有操作均适用于这些按钮。请给我一些提示。
您的视图模型是否绑定到您的视图?
DataContext = new MainViewModel();
或
<Window.DataContext>
<local:MainViewModel/>
</Window.DataContext>
像Isaudon说我还没有
DataContext = new MainViewModel();
将其添加到MainWindow.xaml.cs之后,实现工作便完成了:
<Button Content="Annotate"
CommandParameter="{Binding}"
Command="{Binding DataContext.ShowImageCommand,
RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type local:MainWindow}}}" />