Instead of having one GotFocus-trigger for each textbox in a grid, you can have it at Grid-level.
XAML:
<Window x:Class="Test.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" > <Grid GotFocus="Grid_GotFocus" LostFocus="Grid_LostFocus"> <TextBox Height="23" Margin="12,12,12,0" x:Name="textBox1" VerticalAlignment="Top" /> <TextBox Margin="12,41,12,0" x:Name="textBox2" Height="23" VerticalAlignment="Top" /> </Grid> </Window>
Codebehind:
using System.Windows; using System.Windows.Controls; namespace Test { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Grid_GotFocus( object sender , RoutedEventArgs e ) { if ( e.Source is TextBox ) { TextBox t = e.Source as TextBox; MessageBox.Show( t.Name + " Got focus" ); } } private void Grid_LostFocus( object sender , RoutedEventArgs e ) { if ( e.Source is TextBox ) { TextBox t = e.Source as TextBox; MessageBox.Show( t.Name + " Lost focus" ); } } } }
Useful for validations.
For example – if you want to process names and values of all textboxes as soon as user is leaving a textbox, you can in the LostFocus eventhandler do this:
private void Grid_LostFocus( object sender , RoutedEventArgs e ) { if ( e.Source is TextBox ) { int count = VisualTreeHelper.GetChildrenCount(theGrid); string u = string.Empty; for ( int i = 0; i < count; i++ ) { object o = VisualTreeHelper.GetChild( theGrid , i ); if ( o is TextBox ) { TextBox t = o as TextBox; u += t.Name + ": " + t.Text + Environment.NewLine; } } MessageBox.Show( u ); } }
Advertisements
Leave a Reply