次の方法で共有


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

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

この例は、拡張アプリケーション マークアップ言語 (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>

次の分離コードは、 GotFocusLostFocus イベント ハンドラーを作成します。 Buttonがキーボード フォーカスを取得すると、BackgroundButtonが赤に変更されます。 Buttonがキーボード フォーカスを失うと、BackgroundButtonが白に戻ります。

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

こちらも参照ください