tags:

views:

24

answers:

1

I have a Window that has two primary areas. One is a TextBox inside of a ScrollViewer and the other is a TabControl. I want to have a red border around the part that currently has focus, so I wrote the following code to do that

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>

Code

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);
    }
}

The problem is that if I click on the TextBox it does not update the border around the ScrollViewer. If I click on a Tab in the TabControl it updates the border so that I can see the border, but doesn't "remove" it when I click somewhere else. Is there some better way to do this?

+2  A: 

First off, I'd highly recommend not using code and keeping this all in XAML.

Secondly, I'd also recommend using a Border to do this.

Third, I'd use IsKeyboardFocusedWithin in your style trigger.

<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>
Adam Sills
This is works great. Thanks.
juharr