WP/UWP设置ListView、ListBox选中、鼠标悬停背景/样式

最近抽空一直在边学边写UWP,后台还好,碰见UI的问题经常脑袋大。这是一个简单但是很不容易做到的事情,特别是对于我这种比较懒的。网上查资料少之又少,大部分都是andriod,所以查一个东西往往会花很多时间。

因为经常碰到ListView或者ListBox之类的选中、鼠标悬停样式和自己设置的主题颜色不搭,这时就需要改变这些样式了,而这里我通过ListBox来说明,大致思路其实就是重新定义ListBoxItem的Template。

第一步:去掉所有的样式,也是就是所有样式都不要。

<Style x:Name="MyListBoxItemStyle" TargetType="ListBoxItem">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ListBoxItem">
        <Grid Background="{TemplateBinding Background}">
          <ContentPresenter
              Content="{TemplateBinding Content}"
              Margin="{TemplateBinding Padding}" />
        </Grid>
      </ControlTemplate>
    </Setter.Value>
  </Setter>
</Style>

第二步:通过VisualStateManager来设置鼠标悬停的样式。

  <Style x:Name="MyListBoxItemStyle" TargetType="ListBoxItem">
    <Setter Property="Template">
      <Setter.Value>
        <ControlTemplate TargetType="ListBoxItem">
          <Grid Background="{TemplateBinding Background}">
            <VisualStateManager.VisualStateGroups>
              <VisualStateGroup>
                <!--缺省样式-->
                <VisualState x:Name="Normal" />
                <!--设置鼠标悬停样式-->
                <VisualState x:Name="PointerOver">
                  <Storyboard>
                    <ObjectAnimationUsingKeyFrames 
                        Storyboard.TargetName="ContentBackground"
                        Storyboard.TargetProperty="Background">
                      <DiscreteObjectKeyFrame KeyTime="0" Value="Red" />
                    </ObjectAnimationUsingKeyFrames>
                  </Storyboard>
                </VisualState>
              </VisualStateGroup>
            </VisualStateManager.VisualStateGroups>
            <Grid x:Name="ContentBackground">
              <ContentPresenter
                  Content="{TemplateBinding Content}"
                  Margin="{TemplateBinding Padding}" />
            </Grid>
          </Grid>
        </ControlTemplate>
      </Setter.Value>
    </Setter>

第三步:加上选中样式,这里思路同鼠标悬停就不列代码了。

补充:博主改这个样式步骤其实恰恰相反,通过复制C:\Program Files (x86)\Windows Kits\10\DesignTime\CommonConfiguration\Neutral\UAP\10.0.10240.0\Generic\generic.xaml文件中的样式一步步删减最后得到自己需要的样式。同理再遇见其他控件样式的问题,就可以通过这个方法来解决。

posted @ 2015-10-23 22:43  飞舞的叶子  阅读(3831)  评论(2编辑  收藏  举报