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文件中的樣式一步步刪減最后得到自己需要的樣式。同理再遇見其他控件樣式的問題,就可以通過這個方法來解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM