简单的目标。点击 %$^%# 小丑...得到一个 *&^$^$ 消息框。我希望能够对单击列表视图的单行做出反应。事实证明这是非常困难的。我知道正在应用 ItemContainerStyle ...所有项目都被推到右边。那么为什么事件没有触发呢?
这是 XAML:
<Window x:Class="TryListView.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:TryListView"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525"
Background="Black">
<Grid Background="Transparent">
<ListView Grid.Row="1" x:Name="lbClowns" Background="Transparent">
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Border Margin="5" BorderBrush="White" BorderThickness="1">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBlock Margin="5,0,0,0" Grid.Row="0" x:Name="NameTxt" TextWrapping="Wrap" Text="{Binding ClownName}" FontSize="28" Foreground="White"/>
<TextBlock Margin="5,0,0,0" Grid.Row="1" x:Name="TrickTxt" TextWrapping="Wrap" Foreground="White" FontSize="18" Text="{Binding ClownTrick}" />
</Grid>
</Border>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Right" />
<EventSetter Event="MouseLeftButtonDown" Handler="KlownKlicked" />
</Style>
</ListView.ItemContainerStyle>
</ListView>
</Grid>
</Window>
这是代码隐藏:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
namespace TryListView
{
public class Clown
{
public string ClownName { get; set; }
public string ClownTrick { get; set; }
}
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
PopulateMyListView();
}
private void PopulateMyListView()
{
var ListOClownz = new List<Clown>()
{
new Clown() { ClownName = "Krusty", ClownTrick="Juggling" },
new Clown() { ClownName = "Pennywise", ClownTrick="Human Sacrifice" },
new Clown() { ClownName = "Shakes", ClownTrick="Vomiting" },
new Clown() { ClownName = "Bozo", ClownTrick="Swordfighting" },
};
lbClowns.ItemsSource = ListOClownz;
}
private void KlownKlicked(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("Congratulations, you klicked a klown. Now get lost.");
}
}
}