この例では、 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>
次の分離コードは、 GotFocus と LostFocus イベント ハンドラーを作成します。 Buttonがキーボード フォーカスを取得すると、BackgroundのButtonが赤に変更されます。 Buttonがキーボード フォーカスを失うと、BackgroundのButtonが白に戻ります。
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
こちらも参照ください
GitHub で Microsoft と共同作業する
このコンテンツのソースは GitHub にあります。そこで、issue や pull request を作成および確認することもできます。 詳細については、共同作成者ガイドを参照してください。
.NET Desktop feedback