如何:處理 ListView 中每個項目的 MouseDoubleClick 事件
若要處理 ListView 中項目的事件,您必須將事件處理程序新增至每個 ListViewItem。 當 ListView 繫結至資料來源時,您不會明確建立 ListViewItem,但您可以將 EventSetter 新增至 ListViewItem 樣式來處理每個項目的事件。
範例
下列範例會建立資料繫結 ListView,並建立 Style,已新增事件處理程式至每個 ListViewItem。
<!--XmlDataProvider is defined in a ResourceDictionary,
such as Window.Resources-->
<XmlDataProvider x:Key="InventoryData" XPath="Books">
<x:XData>
<Books xmlns="">
<Book ISBN="0-7356-0562-9" Stock="in" Number="9">
<Title>XML in Action</Title>
<Summary>XML Web Technology</Summary>
</Book>
<Book ISBN="0-7356-1370-2" Stock="in" Number="8">
<Title>Programming Microsoft Windows With C#</Title>
<Summary>C# Programming using the .NET Framework</Summary>
</Book>
<Book ISBN="0-7356-1288-9" Stock="out" Number="7">
<Title>Inside C#</Title>
<Summary>C# Language Programming</Summary>
</Book>
<Book ISBN="0-7356-1377-X" Stock="in" Number="5">
<Title>Introducing Microsoft .NET</Title>
<Summary>Overview of .NET Technology</Summary>
</Book>
<Book ISBN="0-7356-1448-2" Stock="out" Number="4">
<Title>Microsoft C# Language Specifications</Title>
<Summary>The C# language definition</Summary>
</Book>
</Books>
</x:XData>
</XmlDataProvider>
<!--The Style is defined in a ResourceDictionary,
such as Window.Resources-->
<Style TargetType="ListViewItem">
<EventSetter Event="MouseDoubleClick" Handler="ListViewItem_MouseDoubleClick"/>
</Style>
<ListView ItemsSource="{Binding Source={StaticResource InventoryData}, XPath=Book}">
<ListView.View>
<GridView>
<GridViewColumn Width="300" Header="Title"
DisplayMemberBinding="{Binding XPath=Title}"/>
<GridViewColumn Width="150" Header="ISBN"
DisplayMemberBinding="{Binding XPath=@ISBN}"/>
</GridView>
</ListView.View>
</ListView>
下列範例會處理 MouseDoubleClick 事件。
void ListViewItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
XmlElement book = ((ListViewItem) sender).Content as XmlElement;
if (book == null)
{
return;
}
if (book.GetAttribute("Stock") == "out")
{
MessageBox.Show("Time to order more copies of " + book["Title"].InnerText);
}
else
{
MessageBox.Show(book["Title"].InnerText + " is available.");
}
}
Private Sub ListViewItem_MouseDoubleClick(ByVal sender As Object, _
ByVal e As MouseButtonEventArgs)
Dim lvi As ListViewItem = CType(sender, ListViewItem)
Dim book As XmlElement = CType(lvi.Content, XmlElement)
If book.GetAttribute("Stock") = "out" Then
MessageBox.Show("Time to order more copies of " + book("Title").InnerText)
Else
MessageBox.Show(book("Title").InnerText + " is available.")
End If
End Sub
注意
雖然最常見的方式是將 ListView 繫結至資料來源,但不論您是否明確建立 ListViewItem,都可以使用樣式將事件處理程式新增至非資料繫結 ListView 中的每個 ListViewItem。 如需明確和隱含建立 ListViewItem 控制項的詳細資訊,請參閱 ItemsControl。