在WPF中,如何在具有焦点的窗口部分周围放置边框?

juh*_*arr 4 wpf focus border

我有一个有两个主要区域的窗口.一个是ScrollViewer内部的TextBox,另一个是TabControl.我想在当前具有焦点的部分周围有一个红色边框,所以我编写了以下代码来做到这一点

XAML

<ScrollViewer BorderBrush="Red" 
              BorderThickness="0"
              GotFocus="Border_GotFocus"  
              LostFocus="Border_LostFocus">
    <TextBox/>
</ScrollViewer>
<TabControl BorderBrush="Red" 
            BorderThickness="0"
            GotFocus="Border_GotFocus"  
            LostFocus="Border_LostFocus">
</TabControl>
Run Code Online (Sandbox Code Playgroud)

private void Border_LostFocus(object sender, RoutedEventArgs e)
{
    var control = sender as Control;
    if (control != null)
    {
        control.BorderThickness = new Thickness(0);
    }
}

private void Border_GotFocus(object sender, RoutedEventArgs e)
{
    var control = sender as Control;
    if (control != null)
    {
        control.BorderThickness = new Thickness(2);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我单击TextBox,它不会更新ScrollViewer周围的边框.如果我单击TabControl中的Tab,它会更新边框,以便我可以看到边框,但是当我点击其他地方时不会"删除"它.有没有更好的方法来做到这一点?

Ada*_*lls 6

首先,我强烈建议不要使用代码并将其保留在XAML中.

其次,我还建议使用a Border来做到这一点.

第三,我在你的样式触发器中使用IsKeyboardFocusedWithin.

<Window.Resources>
    <Style x:Key="FocusedBorder" TargetType="Border">
        <Setter Property="BorderThickness" Value="2"></Setter>
        <Setter Property="BorderBrush" Value="Transparent"></Setter>
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="BorderBrush" Value="Red"></Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>
<StackPanel Width="400">
    <ScrollViewer>
        <Border Style="{StaticResource FocusedBorder}">
            <TextBox>
            </TextBox>
        </Border>
    </ScrollViewer>
    <TabControl>
        <TabItem Header="Foo">
            <Border Style="{StaticResource FocusedBorder}">
                <TextBox></TextBox>
            </Border>
        </TabItem>
        <TabItem Header="Bar">
            <Border Style="{StaticResource FocusedBorder}">
                <TextBox></TextBox>
            </Border>
        </TabItem>
    </TabControl>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)