Pages

Sunday, 1 February 2009

IsVisibleChanged

I have the following code which is trying to detect that I’ve clicked on a button and my UserControl is now visible, so I want to set focus to a sensible control in that usercontrol.

void UCBBNotes_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
  if ((bool)e.NewValue == true)
  {
     bool a = txtNotes.Focus();
     // a returns false 
     txtNotes.UpdateLayout();
     bool b = txtNotes.Focus();
     // b returns true
  }
}

So, when reacting to certain events such as “IsVisibleChanged”, the event is called before the layout has updated all the child controls. So txtNotes.Focus() fails because txtNotes.IsVisible = False at that point.

This can either be fixed as above by forcing an UpdateLayout by the Dispatcher – which probably isn’t ideal. Or, instead of watching for the usercontrol to become visible, watch for the textbox we want to focus upon to become visible, like this :

void txtNotes_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
  if ((bool)e.NewValue == true)
  {
     txtNotes.Focus();
  }
}

No comments: