views:

725

answers:

2

I'm displaying a very big tree with a lot of items in it. Each of these items shows information to the user through its associated UserControl control, and this information has to be updated every 250 milliseconds, which can be a very expensive task since I'm also using reflection to access to some of their values. My first approach was to use the IsVisible property, but it doesn't work as I expected.

Is there any way I could determine whether a control is 'visible' to the user?

Note: I'm already using the IsExpanded property to skip updating collapsed nodes, but some nodes have 100+ elements and can't find a way to skip those which are outside the grid viewport.

+1  A: 

You can use this little helper function I just wrote that will check if an element is visible for the user, in a given container. The function returns true if the element is partly visible. If you want it to be fully visible, replace the last ligne by rect.Contains(bounds).

private bool IsUserVisible(FrameworkElement element, FrameworkElement container) {
 if (!element.IsVisible)
  return false;
 Rect bounds = element.TransformToAncestor(container).TransformBounds(new Rect(0.0, 0.0, element.ActualWidth, element.ActualHeight));
 Rect rect = new Rect(0.0, 0.0, container.ActualWidth, container.ActualHeight);
 return rect.Contains(bounds.TopLeft) || rect.Contains(bounds.BottomRight);
}

In your case, element will be your user control, and container your Window.

Julien Lebosquain
+1  A: 

Use these properties for the containing control:

VirtualizingStackPanel.IsVirtualizing="True" 
VirtualizingStackPanel.VirtualizationMode="Recycling"

and then hook up listening to your data item's INotifyPropertyChanged.PropertyChanged subscribers like this

    public event PropertyChangedEventHandler PropertyChanged
    {
        add
        {
            Console.WriteLine(
               "WPF is listening my property changes so I must be visible");
        }
        remove
        {
            Console.WriteLine("WPF unsubscribed so I must be out of sight");
        }
    }

For more detailed info see: http://joew.spaces.live.com/?%5Fc11%5FBlogPart%5FBlogPart=blogview&%5Fc=BlogPart&partqs=cat%3DWPF

Timoi