项目中利用ListBox来动态布局,但控件自带的mouseover和select等方法均定制了高亮。为了屏蔽,在网上搜到如下代码:
<Style x:Key="ListBoxItemStyleTransparent" TargetType="ListBoxItem"> <Setter Property="Padding" Value="3"/> <Setter Property="HorizontalContentAlignment" Value="Left"/> <Setter Property="VerticalContentAlignment" Value="Top"/> <Setter Property="Background" Value="Transparent"/> <Setter Property="BorderThickness" Value="1"/> <Setter Property="TabNavigation" Value="Local"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="ListBoxItem"> <Grid Background="{TemplateBinding Background}"> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal"/> <VisualState x:Name="MouseOver"> </VisualState> <VisualState x:Name="Disabled"> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetName="contentPresenter" Storyboard.TargetProperty="Opacity"> <SplineDoubleKeyFrame KeyTime="0" Value=".55"/> </DoubleAnimationUsingKeyFrames> </Storyboard> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="SelectionStates"> <VisualState x:Name="Unselected"/> <VisualState x:Name="Selected"> </VisualState> </VisualStateGroup> <VisualStateGroup x:Name="FocusStates"> <VisualState x:Name="Focused"> <Storyboard> <ObjectAnimationUsingKeyFrames Duration="0" Storyboard.TargetName="FocusVisualElement" Storyboard.TargetProperty="Visibility"> <DiscreteObjectKeyFrame KeyTime="0"> <DiscreteObjectKeyFrame.Value> <Visibility>Visible</Visibility> </DiscreteObjectKeyFrame.Value> </DiscreteObjectKeyFrame> </ObjectAnimationUsingKeyFrames> </Storyboard> </VisualState> <VisualState x:Name="Unfocused"/> </VisualStateGroup> </VisualStateManager.VisualStateGroups> <Rectangle x:Name="fillColor" Fill="#FFBADDE9" RadiusX="1" RadiusY="1" IsHitTestVisible="False" Opacity="0"/> <Rectangle x:Name="fillColor2" Fill="#FFBADDE9" RadiusX="1" RadiusY="1" IsHitTestVisible="False" Opacity="0"/> <ContentPresenter x:Name="contentPresenter" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}"/> <Rectangle x:Name="FocusVisualElement" Stroke="#FF6DBDD1" StrokeThickness="1" RadiusX="1" RadiusY="1" Visibility="Collapsed"/> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
核心思想:通过设置颜色为透明色来屏蔽。
若把该Style放在具体页面上可以用一下两种方法进行设置
1 页面上设置
<ListBox x:Name="ListBox1" Background="LightGray" Width="854" Height="530" VerticalAlignment="Top" HorizontalAlignment="Left" ItemContainerStyle="{StaticResource ListBoxItemStyleTransparent}"/>
2 后台代码设置
//style为页面的资源(放在页面的UserControl.Resource中) item.Style = this.Resources["ListBoxItemStyleTransparent"] as Style; // style为全局资源(放在全局的一个Xaml文件中) item.Style =Application.Current.Resources["ListBoxItemStyleTransparent"] as Style;