今天在项目中,遇到一个问题,具体需求为:
我有一个listBox控件:
<ListBox x:Name="lstMyDesktop"
Margin="7,4,0,8"
BorderThickness="0"
SelectionChanged="lstMyDesktop_SelectionChanged"
SelectionMode="Single"
DisplayMemberPath="DesktopName"
Style="{StaticResource MyDeskTopListBoxStyle}"
ItemContainerStyle="{StaticResource MyDeskTopListBoxItemStyle}">
........
</ListBox >
可以看出我应用了ItemContainerStyle 样式,大致内容为
<Style x:Key="MyDeskTopListBoxItemStyle"
TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Grid Background="{TemplateBinding Background}">
<Grid x:Name="grdSelect"
Opacity="0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Image Width="12"
Grid.Column="0"
Stretch="None"
Margin="5,0,0,0"
VerticalAlignment="Center"
Source="/SLClient.Styles;component/Images/icon_desktopSelect.png"
x:Name="mouseSelectImg" />
<ctrl:EditableTextBlock x:Name="txtmouseName"
Grid.Column="1"
Cursor="{TemplateBinding Cursor}"
Margin="{TemplateBinding Padding}"
Foreground="{StaticResource CommonSolidBrush1}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Content="{Binding DesktopName, Mode=TwoWay}" />
<ctrl:ImageButton x:Name="btnMouseClose"
ImageNormal="/SLClient.Styles;component/Images/newDesktopClose_normal.png"
ImageOver="/SLClient.Styles;component/Images/newDesktopClose_hover.png"
Style="{StaticResource ImageButtonStyle}"
Grid.Column="2" />
</Grid>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
主要实现的一个功能就是点击名为btnMouseClose的button的按钮,完成对ListBox的item的删除,当我删除当前的item时,然后将listBox的SelectIndex至为第一项,即listBox.SelectIndx=0。
但是出现的bug是触发完btn的MouseLeftButtonDown事件后再次触发了listBox的SelectionChanged事件,而且SelectedItem为null值,即出现的结果是无法选中第一项元素。
原来导致问题的根本原因在于button作为ListBoxItem的Template中的一个元素,那么他存在路由事件,即在btn按钮的MouseLeftButtonDown事件中加上e.Handled = true,即不会再次触发listBox的SelectionChanged事件,那么结局就完美啦,得到了我想要的效果
╮(╯▽╰)╭,几费周折啊,终于搞定了,希望这篇文章能给大家带来帮助,少走弯路,我也由此而牢牢记住~