共用方式為


如何:使用焦點事件變更項目的色彩

此範例示範如何使用 GotFocusLostFocus 事件以在元素取得和失去焦點時變更元素的色彩。

這個範例包含 Extensible Application Markup Language (XAML) 檔案和程式碼後置檔案。

範例

以下 XAML 會建立由兩個 Button 物件組成的使用者介面,並將 GotFocusLostFocus 事件的事件處理常式附加到 Button 物件。

<StackPanel>
  <StackPanel.Resources>
    <Style TargetType="{x:Type Button}">
      <Setter Property="Height" Value="20"/>
      <Setter Property="Width" Value="250"/>
      <Setter Property="HorizontalAlignment" Value="Left"/>
    </Style>
  </StackPanel.Resources>
  <Button
      GotFocus="OnGotFocusHandler"
      LostFocus="OnLostFocusHandler">Click Or Tab To Give Keyboard Focus</Button>
  <Button
      GotFocus="OnGotFocusHandler"
      LostFocus="OnLostFocusHandler">Click Or Tab To Give Keyborad Focus</Button>
</StackPanel>

下列程式碼後置會建立 MouseEnterMouseLeave 事件處理常式。 當 Button 取得鍵盤焦點時,ButtonBackground 會變更為紅色。 當 Button 失去鍵盤焦點時,ButtonBackground 會變更回白色。

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();
    }

    // Raised when Button gains focus.
    // Changes the color of the Button to Red.
    private void OnGotFocusHandler(object sender, RoutedEventArgs e)
    {
        Button tb = e.Source as Button;
        tb.Background = Brushes.Red;
    }
    // Raised when Button losses focus.
    // Changes the color of the Button back to white.
    private void OnLostFocusHandler(object sender, RoutedEventArgs e)
    {
        Button tb = e.Source as Button;
        tb.Background = Brushes.White;
    }
}
Partial Public Class Window1
    Inherits Window

    Public Sub New()
        InitializeComponent()
    End Sub

    'raised when Button gains focus. Changes the color of the Button to red.
    Private Sub OnGotFocusHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim tb As Button = CType(e.Source, Button)
        tb.Background = Brushes.Red
    End Sub

    'raised when Button loses focus. Changes the color back to white.
    Private Sub OnLostFocusHandler(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim tb As Button = CType(e.Source, Button)
        tb.Background = Brushes.White
    End Sub
End Class

另請參閱