生活随笔
收集整理的這篇文章主要介紹了
WPF ListBox样式去掉默认选中效果
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
次用到ListBox的時候,鼠標懸浮時,ListBoxItem的默認樣式太丑了,設置了ItemTemplate也不管用,像這樣的:
經過幾次嘗試后,終于解決了這個問題,記錄一下,以后就不用到處百度找了。。。
其實很簡單,只需定義一個ItemContainerStyle,即可。
<Style x:Key="ItemContainerStyle1" TargetType="ListBoxItem"><Setter Property="SnapsToDevicePixels" Value="true"/><Setter Property="FocusVisualStyle" Value="{x:Null}"/><Setter Property="Template"><Setter.Value><ControlTemplate TargetType="ListBoxItem"><Border Name="Border"Padding="7" Background="Transparent" SnapsToDevicePixels="True"><ContentPresenter /></Border><ControlTemplate.Triggers><Trigger Property="IsSelected" Value="true"><Setter TargetName="Border" Property="Background" Value="Green"/><Setter Property="Foreground" Value="White"/></Trigger><Trigger Property="IsEnabled" Value="false"><Setter Property="Foreground" Value="LightGray"/></Trigger></ControlTemplate.Triggers></ControlTemplate></Setter.Value></Setter>
</Style>
原來只要設置了一下模板就好了。。。
剛做出來時,我心里一w頭***狂奔。。。
下面是測試的代碼:
<StackPanel HorizontalAlignment="Stretch" ><TextBlock Text="{Binding CurrentItem,StringFormat={}選中項:{0}}" FontSize="18"/><ListBox x:Name="lbPersonList" SelectedValue="{Binding CurrentItem}"SelectedValuePath="Text"ItemContainerStyle="{StaticResource ItemContainerStyle1}"><TextBlock Text="Hello,world"/><TextBlock Text="你好"/><TextBlock Text="你也好"/></ListBox></StackPanel>
設置了綁定的選中項value的路徑,這樣就可以在后臺代碼中獲取選中項了。
后臺代碼:
public partial class IconFontButtonDemo : Window, INotifyPropertyChanged{private string _currentItem;public event PropertyChangedEventHandler PropertyChanged;public string CurrentItem{get { return _currentItem; }set{_currentItem = value;PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(CurrentItem)));}}public IconFontButtonDemo(){InitializeComponent();DataContext = this;}}
效果是這樣的:
好了,就到這里了,wpf,踩坑中
總結
以上是生活随笔為你收集整理的WPF ListBox样式去掉默认选中效果的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。