【发布时间】:2019-11-18 15:23:13
【问题描述】:
我有一个带有 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才能使用命令绑定。请分享列表视图的完整 xaml 以及MainViewModel设置为数据上下文的位置 -
通常你有你的 ViewModel 公开命令。并使用按钮或菜单项来表示这些命令。
-
我有
<Window x:Class="blabla.MainWindow" Title="MainWindow" Height="450" Width="800"> <Grid DataContext="{Binding MainViewModel, Source={StaticResource Locator}}"> **here the rest of interface goes** </Grid>
标签: c# button mvvm binding label