c# - 为什么 IsFocused 没有在 Label 上触发

标签 c# wpf events xaml controls

我只想定义一个触发器,在以下情况下更改标签背景颜色: 专注,但是没效果。对按钮进行同样的操作就可以了。有什么问题吗?!?!我在边框和文本 block 方面也遇到了同样的问题。

更新代码xaml:

  <Window.Resources>
    <SolidColorBrush x:Key="GridLineBrush" Color="#8DAED9" />
    <SolidColorBrush x:Key="HeaderWeekDayBackground" Color="#A5BFE1" />
    <Style x:Key="borderStyle" TargetType="Control">
      <Setter Property="Background" Value="{StaticResource HeaderWeekDayBackground}" />
      <Style.Triggers>
        <Trigger Property="IsFocused" Value="true">
          <Setter Property="Background" Value="Blue" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </Window.Resources>

  <Grid>
    <Grid.RowDefinitions>
      <RowDefinition/>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Style="{StaticResource borderStyle}" 
        Grid.Row="0" >
    </Button>
    <Label Focusable="True" Style="{StaticResource borderStyle}" 
        Grid.Row="1" >
    </Label>
  </Grid>
</Window>

最佳答案

并非所有控件默认都是可聚焦的,请将 Focusable 设置为 true 看看是否有帮助。

您可能遇到的一个问题是,默认情况下,Label 不会从鼠标事件接收焦点。

我不知道是否有一种干净的仅 XAML 方法来设置焦点,但您可以处理鼠标事件:

<Label Focusable="True" Content="Test" MouseLeftButtonUp="Label_MouseLeftButtonUp">
    <Label.Style>
        <Style TargetType="Label">
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Red" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Label.Style>
</Label>
//Note that this is not a "proper" click.
private void Label_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
    var label = sender as Label;
    label.Focus();
}

关于c# - 为什么 IsFocused 没有在 Label 上触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6658853/

相关文章:

C# 在运行时返回没有类型参数的泛型类型

c# - 如何在 Windows 上调试 .NET Core 3 崩溃

c# - MVVM 在单击时更改网格的背景颜色

javascript - 使用 window.onscroll 事件检测页面/框架滚动

c# - Azure 网络应用 : Web sockets abort after 100 seconds

c# - UWP:检测应用程序获得/失去焦点

WPF MVVM - 模型由什么组成

javascript - iOS 7 onchange 事件在 iPad 3+Mini 中被破坏//需要变通

javascript - 传递带参数的函数时不触发单击事件

c# - 等待一个线程在循环中存活是好习惯吗?