WPF UserControl焦点

时间:2011-09-29 12:42:15

标签: wpf user-controls focus

我有一个包含UserControl的{​​{1}}子类,后者又包含一对Grid和一个TextBlock(其中还包含Border )。请参阅下面的代码。

TextBlock

当我的 <UserControl x:Class="ProjectNS.MyUserControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:my="clr-namespace:ProjectNS" mc:Ignorable="d" Height="49" Width="150" BottomResizeLocked="True" TopResizeLocked="True" MoveLocks="Vertical" Margin="0,-4" Focusable="True"> <my:MyUserControl.Resources> <Style x:Key="BorderStyle" TargetType="Border"> <Setter Property="Background" Value="Blue"/> <Setter Property="BorderBrush" Value="Blue"/> <Style.Triggers> <DataTrigger Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type my:GanttBar}}, Path=IsKeyboardFocusWithin}" Value="True"> <Setter Property="Background" Value="{StaticResource SelectedGanttBarBackGroundBrush}"/> <Setter Property="BorderBrush" Value="{StaticResource SelectedGanttBarBorderBrush}"/> </DataTrigger> </Style.Triggers> </Style> </my:MyUserControl.Resources> <Grid> <Grid.RowDefinitions> <RowDefinition Height="2*" /> <RowDefinition Height="3*" /> <RowDefinition Height="2*" /> </Grid.RowDefinitions> <Label FontSize="8.5" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="4,0,0,0" Foreground="Green" /> <Border Grid.Row="1" CornerRadius="5" BorderThickness="1.5" Style=" {StaticResource BorderStyle}" FocusVisualStyle="{StaticResource SelectedBorderStyle}" Focusable="True" > <Label FontSize="10" HorizontalAlignment="Center" FontWeight="Bold" VerticalAlignment="Top" Foreground="White" Margin="0,2,0,0" /> </Border> <Label HorizontalAlignment="Right" FontSize="8.5" Grid.Row="2" VerticalAlignment="Top" Margin="0,0,4,0" Foreground="Red" /> </Grid> </my:MyUserControl> 获得焦点时,我正试图让嵌入边框的颜色改变颜色,但我不能为我的生活找出当我点击控件时实际获得焦点的内容。我已经尝试对每个控件使用UserControl事件,并且一旦程序运行就不会触发。

1 个答案:

答案 0 :(得分:1)

在属性IsKeyboardFocusWithin上使用DataTrigger。我不是肯定的确切语法,但它应该看起来像这样:

<Style TargetType="{x:Type Border}">
    <Setter Property="BorderBrush" Value="Red" />
    <Style.Triggers>

        <!-- Will change Border color when KeyboardFocus inside Border -->
        <Trigger Property="IsKeyboardFocusWithin" Value="True">
            <Setter Property="BorderBrush" Value="Green" />
        </Trigger>

        <!-- Will change Border color when UserControl contains KeyboardFocus -->
        <DataTrigger Binding="{Binding RelativeSource={RelativeSource 
            AncestorType={x:Type local:MyUserControl}}, 
            Path=IsKeyboardFocusWithin}" Value="True">
            <Setter Property="BorderBrush" Value="Blue" />
        </DataTrigger>

    </Style.Triggers>
</Style>