Kris' Blog

RSS feed

Visibility.Visible != IsVisible

Today, Robert and I spent a while trying to figure out why we couldn’t give focus to a TextBox we added dynamically. Calling textBox.Focus() was always returning false, yet we could click on it to focus.

Reading the WPF focus overview, Focus() returns false if either IsEnabled, IsVisible or Focusable are false — well it defaults to being enabled, visible and focusable so why isn’t it working?

IsVisible is calculated during the Layout pass, which isn’t going to happen on this dispatcher operation. During this time, textBox.Visibility will return Visibility.Visible and textBox.IsVisible will return false.

Determination of the IsVisible value takes all factors of layout into account. In contrast, Visibility, which is a settable property, only indicates the intention to programmatically make an element visible or invisible.

textBox = new TextBox();
AddChild(textBox);
// textBox.IsVisible == false
textBox.UpdateLayout();
// textBox.IsVisible == true
textBox.Focus() // returns true

In general, read-only properties, especially dependency properties registered as read-only, will need an UpdateLayout (I wouldn’t do that a lot) or you will need to BeginInvoke your work on the Dispatcher to wait for layout.


4 Comments »

  1. Hey Kris,

    I am working on WPF. Where in which on the UI i have one button and a Image component. As soon as i launch the apps, the Image component will be disabled. When i press button, then only that Image component is enabled.

    So i am trying to write code as image1.Isvisible = true. But as your article says. Is a read only component. So how can i change the visibility of this object?? I mean, how can i set values of IsVisible property in WPF?

  2. IsVisible is readonly because it is calculated at layout and is useful for triggers. To set visibility use the Visibility property.

  3. Thanks for this post, I struggled with why I couldn’t set the focus on my textbox for a few hours but your explanation makes perfect sense! I am going to post a link on our blog site…

    Sean

  4. Thanks for the post!

    I was struggling trying to set focus on a textbox added at runtime!

Leave a comment