![](/img/trans.png)
[英]Need to trigger an event when ListBoxItem is clicked in ControlTemplate
[英]Need to catch event of the pressing ListBoxItem
在我的WPF程序中,我有一个ListBox
组件和一些ListBoxItems
。 当我按下列表的元素时,我需要捕获事件,但我的代码不起作用:
private void mailsListBox_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
MessageBox.Show("-------------"); // even this doesn't work
switch (mailsListBox.SelectedIndex)
{
// this doesn't work too...
case 0: MessageBox.Show("00"); break;
case 1: MessageBox.Show("11"); break;
case 2: MessageBox.Show("22"); break;
default: break;
}
}
我应该捕获事件MouseLeftButtonDown
吗?
<TabItem Header="Mail" BorderThickness="0" Margin="0" IsSelected="True">
<Grid Background="#FFE5E5E5" Margin="0,5,0,0">
<ListBox x:Name="mailsListBox" MouseLeftButtonDown="mailsListBox_MouseLeftButtonDown" >
<ListBoxItem Content="..." Margin="0,0,0,1"/>
<ListBoxItem Content="..." Margin="0,0,0,1" />
</ListBox>
</Grid>
</TabItem>
我认为如果你处理SelectionChanged事件会更好。
正如tagaPdyk所说,你应该实际捕获SelectionChanged或SelectedIndexChanged事件事件,如下所示:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
//maybe check if there actually is a selection
if(listBox1.SelectedItems[0] != null)
{
var item = listBox1.SelectedItems[0];
//do something with your item
}
}
您实际上可以在列表框中获取所有选定的项目(返回一个array
),或者只使用listBox1.SelectedItems[0]
获取第一个项目。 在控件的properties
您可以定义是否需要多选。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.