WPF ListBox 触发器不适用于 IsFocused 属性 [英] WPF ListBox Trigger not working for IsFocused Property

查看:18
本文介绍了WPF ListBox 触发器不适用于 IsFocused 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的 ListBox 设置样式并在其周围显示一个 Border.我想在 ListBox 获得焦点时隐藏这个 Border:

I want to style my ListBox and display a Border around it. I want to hide this Border when ListBox gets focus:

<Trigger Property="IsFocused" Value="True">
    <Setter Property="Visibility" TargetName="border" Value="Collapsed"/>
</Trigger>

我也在 TextBox 中使用同样的东西,它工作正常.为什么这个 TriggerListBox 不起作用?

Same thing I'm using in TextBox also and it is working properly. Why is this Trigger not working for ListBox?

我的 ListBox 有这个 Style:

<ControlTemplate TargetType="{x:Type local:ListBox}">
    <Border SnapsToDevicePixels="true" x:Name="Bd" CornerRadius="5"
            Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}" Padding="1">
        <Grid>
            <local:ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
            </local:ScrollViewer>
            <Border CornerRadius="5" Background="Red" x:Name="border">
                <TextBlock VerticalAlignment="Center" FontWeight="Bold" Foreground="White"
                           Text="{TemplateBinding Message}" FontFamily="Courier New" />
            </Border>
        </Grid>
    </Border>
</DockPanel>
    <ControlTemplate.Triggers>
        <Trigger Property="IsFocused" Value="True">
            <Setter Property="Visibility" TargetName="border" Value="Collapsed"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Background" TargetName="Bd"
                    Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
        </Trigger>
        <Trigger Property="IsGrouping" Value="true">
            <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

推荐答案

对于 ListBox IsFocused 不更新,因为焦点没有转到列表框,而是转到列表框覆盖的区域,表示包含 ListBoxItems 的 ItemsPresenter.我有一个解决这个问题的方法.在 ListBox 的 MouseDown 事件处理程序中,我调用 Focus() 方法.它将 IsFocused 属性设置为 true 并使我的触发器工作.

For ListBox IsFocused not updating because focus does not goes to list box but it goes to area covered by listbox means the ItemsPresenter which contains ListBoxItems. I have got a workaround to this problem. In MouseDown event handler of the ListBox, I call Focus() method. It sets the IsFocused property to true and make my trigger working.

这篇关于WPF ListBox 触发器不适用于 IsFocused 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆