WPF 命令绑定 ListViewItem。单击 ListBoxItem 时执行命令

WPF Command Binding ListViewItem. Execute command when ListBoxItem clicked

有效(命令):

<Button Command="{Binding LoadMainCommand, Mode=OneTime}">
    <TextBlock Text="Testo" />
</Button>

以及如何在此处实现(命令)-> (ListViewItem)?:

<ListView>
    <ListViewItem>
        <StackPanel>
            <Image Source="../img.png">
        </StackPanel>
        <ListViewItem.ToolTip>
            <ToolTip Content="Testo" Style="{StaticResource tt_style}"/>
        </ListViewItem.ToolTip>
    </ListViewItem>
</ListView>

如果您想在单击项目(而不是内容)时执行命令,最简单的方法是将 InputBinding 添加到 ListBoxItem:

<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="ListBoxItem">
            <Border Background="{TemplateBinding Background}"
                    BorderBrush="{TemplateBinding BorderBrush}"
                    BorderThickness="{TemplateBinding BorderThickness}">
              <Border.InputBindings>
                <MouseBinding MouseAction="{x:Static MouseAction.LeftDoubleClick}"
                              Command="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=DataContext.SelectPageCommand}"
                              CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=ListView}, Path=SelectedItem}" />
              </Border.InputBindings>

              <ContentPresenter />
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

或者将 ListBoxItem 变成 Button:

<ListView>
  <ListViewItem>

    <!-- You may need to adjust binding path -->
    <Button Command="{Binding LoadMainCommand, Mode=OneTime}">
      <StackPanel>
        <Image Source="../img.png">
      </StackPanel>
    </Button>
    <ListViewItem.ToolTip>
      <ToolTip Content="Testo" Style="{StaticResource tt_style}"/>
    </ListViewItem.ToolTip>
  </ListViewItem>
</ListView>

或者通过设置 ListView.ItemContainerStyle 覆盖 ControlTemplate

<ListView>
  <ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="ListViewItem">

            <!-- You may need to adjust binding path -->
            <Button Command="{Binding LoadMainCommand, Mode=OneTime}"
                    Content="{TemplateBinding Content}" />
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
  </ListView.ItemContainerStyle>
  <ListViewItem>
    <StackPanel>
      <Image Source="../img.png">
    </StackPanel>
    <ListViewItem.ToolTip>
      <ToolTip Content="Testo" Style="{StaticResource tt_style}"/>
    </ListViewItem.ToolTip>
  </ListViewItem>
</ListView>