问题描述
在listbox中鼠标停留添加了一个按钮,点击按钮,将按钮的响应路由到了他的父控件listbox,lsitbox的selectindex的值始终是-1也就是没有被选中,求解,这是为什么呢?<Window.Resources><StyleTargetType="{x:TypeListBoxItem}"><SetterProperty="Template"><Setter.Value><ControlTemplateTargetType="{x:TypeListBoxItem}"><Borderx:Name="PART_Border"Margin="2"Width="150"Height="20"Background="Blue"BorderBrush="Black"BorderThickness="1"><Grid><WrapPanelx:Name="OpationPanel"Opacity="0"HorizontalAlignment="Right"VerticalAlignment="Bottom"><ButtonWidth="24"Height="24"Click="Button_Click"/></WrapPanel></Grid></Border><ControlTemplate.Triggers><TriggerProperty="ListBoxItem.IsMouseOver"Value="True"><SetterProperty="Effect"><Setter.Value><DropShadowEffectBlurRadius="30"Color="Black"Direction="0"Opacity="0.6"RenderingBias="Performance"ShadowDepth="0"/></Setter.Value></Setter><Trigger.EnterActions><BeginStoryboard><Storyboard><DoubleAnimationBeginTime="0:0:0"Storyboard.TargetName="OpationPanel"Storyboard.TargetProperty="Opacity"Duration="0:0:0.4"From="0"To="1"/></Storyboard></BeginStoryboard></Trigger.EnterActions><Trigger.ExitActions><BeginStoryboard><Storyboard><DoubleAnimationBeginTime="0:0:0"Storyboard.TargetName="OpationPanel"Storyboard.TargetProperty="Opacity"Duration="0:0:0.4"From="1"To="0"/></Storyboard></BeginStoryboard></Trigger.ExitActions></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter></Style></Window.Resources><Grid><ListBoxx:Name="listbox1"><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/><ListBoxItemContent="ITEM"/></ListBox>
privatevoidButton_Click(objectsender,EventArgse){//listbox1.Focus();//inti=listbox1.SelectedIndex;////DataRowdr=ListBox.SelectedItemasDataRow;//////stringselectedText=dr["字段"].ToString();//MessageBox.Show(Convert.ToString(i));listbox1.AddHandler(Grid.MouseDownEvent,newRoutedEventHandler(Grid_MouseDown1),true);}privatevoidGrid_MouseDown1(objectsender,RoutedEventArgse){//MessageBox.Show("listbox被点击");inti=listbox1.SelectedIndex;MessageBox.Show(Convert.ToString(i));}
解决方案
解决方案二:
应该获取Button的父控件ListBoxItem,使用类似:this.list.ItemContainerGenerator.IndexFromContainer();
来获取index值。