2010-06-24 42 views
4

我有一個有兩個主要區域的窗口。一個是ScrollViewer內部的TextBox,另一個是TabControl。我想有圍繞當前具有焦點的部分紅色邊框,所以我寫了下面的代碼做在WPF中,如何在具有焦點的窗口部分放置邊框?

的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> 

代碼

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

的問題是,如果我點擊TextBox,它不會更新ScrollViewer的邊框。如果我點擊TabControl中的一個Tab,它會更新邊框,以便我可以看到邊框,但是當我點擊其他地方時不會「移除」邊框。有沒有更好的方法來做到這一點?

回答

5

首先,我強烈建議不要使用代碼並將其全部保存在XAML中。

其次,我還建議使用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> 
+0

這是很好的作品。謝謝。 – juharr 2010-06-24 04:09:30

0

接受的答案對我無效。不過,我想出了一種不使用邊框的方式,仍然可以獲得相同的效果。

下面是用於文本框的樣式。

<Style x:Key="DefaultTextbox" TargetType="{x:Type TextBox}"> 
    <Setter Property="FontSize" Value="14" /> 
    <Setter Property="VerticalAlignment" Value="Center" /> 
    <Setter Property="Margin" Value="5 2 10 2" /> 
    <Setter Property="FontFamily" Value="Arial" /> 
    <Setter Property="FontStyle" Value="Normal" /> 
    <Setter Property="BorderThickness" Value="2" /> 
    <Setter Property="BorderBrush" Value="Transparent" /> 
    <Style.Triggers> 
     <Trigger Property="IsFocused" Value="True" > 
      <Setter Property="BorderBrush" Value="#4E82EC" /> 
     </Trigger> 
    </Style.Triggers> 
</Style> 

我確實遇到了一些麻煩的風格。最初我在Trigger中聲明瞭邊框的厚度和顏色。問題在於當盒子裏有文字時,它似乎跳起來了。繞過跳躍效果是默認聲明邊框厚度,並將邊框設置爲透明,以便在焦點上更改顏色時不會出現跳躍效果。

然後你只需要將樣式設置爲你的文本框:

<TextBox Style="{StaticResource DefaultTextbox}" /> 

這就是你就會看到效果。

Sample of what a focused and non focused textbox looks like