ListBoxItem采用ItemTemplate后选中控件没有SelectedItem
在对于ListBox使用了ItemTemplate的时候常常会遇到这样的情况:
Template中定义了多个控件。当在界面上点击控件时,该控件所在ListboxItem并没有被选中,只有点击控件之外、ListboxItem之内的区域才能选中ListboxItem.
解决方案如下:
<Style TargetType="{x:Type editors:RichTextEdit}"> <Setter Property="IsHitTestVisible" Value="False" /> <Style.Triggers> <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}, AncestorLevel=1}}" Value="True"> <Setter Property="IsHitTestVisible" Value="True" /> </DataTrigger> </Style.Triggers> </Style>
解释:用Setter将该控件的可以点击设置为false。因此每次点击该控件的时候,都是在点击控件背后的ListboxItem。再用DataTrigger使背后Item被选中的时候设置为可以被Hit