生活随笔
收集整理的這篇文章主要介紹了
WPF ListBox样式去掉默认选中效果
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
次用到ListBox的時(shí)候,鼠標(biāo)懸浮時(shí),ListBoxItem的默認(rèn)樣式太丑了,設(shè)置了ItemTemplate也不管用,像這樣的:
經(jīng)過(guò)幾次嘗試后,終于解決了這個(gè)問(wèn)題,記錄一下,以后就不用到處百度找了。。。
其實(shí)很簡(jiǎn)單,只需定義一個(gè)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>
原來(lái)只要設(shè)置了一下模板就好了。。。
剛做出來(lái)時(shí),我心里一w頭***狂奔。。。
下面是測(cè)試的代碼:
<StackPanel HorizontalAlignment="Stretch" ><TextBlock Text="{Binding CurrentItem,StringFormat={}選中項(xiàng):{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>
設(shè)置了綁定的選中項(xiàng)value的路徑,這樣就可以在后臺(tái)代碼中獲取選中項(xiàng)了。
后臺(tái)代碼:
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,踩坑中
總結(jié)
以上是生活随笔為你收集整理的WPF ListBox样式去掉默认选中效果的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。