方法 : フォーカス イベントを使用して要素の色を変更する

要素がフォーカスを取得したときや失ったときに GotFocus イベントおよび LostFocus イベントを使用してその要素の色を変更する方法を次の例に示します。

この例は、Extensible Application Markup Language (XAML) ファイルと分離コード ファイルで構成されています。

使用例

次に示す XAML では、2 つの Button オブジェクトで構成されるユーザー インターフェイスを作成し、GotFocus イベントと LostFocus イベントのイベント ハンドラーを 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>

次の分離コードでは、GotFocus および LostFocus イベント ハンドラーを作成します。 Button がキーボード フォーカスを取得すると、ButtonBackground が赤に変更されます。 Button がキーボード フォーカスを失うと、ButtonBackground が白に変更されます。

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

参照

概念

入力の概要