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,踩坑中

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值