tobsen
tobsen

Reputation: 5398

WPF equivalent to Silverlight "RootVisual"

I am trying to port an application from silverlight to wpf. Unfortunatley I am new to both. Is there an equvivalent to the following Silverlight code in WPF?

        private static Canvas GetCanvas()
        {
            var uc = Application.Current.RootVisual as UserControl;
            if (uc == null)
            {
                return null;
            }
            return uc.FindName("ChoiceCanvas") as Canvas;
        }

Currently I am using

Application.Current.MainWindow.FindName("ChoiceCanvas") as Canvas;

But this doesn't work, perhaps because ChoiceCanvas is something located in a UserControl and not in the MainWindow?

Upvotes: 7

Views: 8699

Answers (3)

Rana Ian
Rana Ian

Reputation: 754

The current window is the root visual.

From MSDN WPF Graphics Rendering Overview:

The root visual is the top-most element in a visual tree hierarchy. In most applications, the base class of the root visual is either Window or NavigationWindow. However, if you were hosting visual objects in a Win32 application, the root visual would be the top-most visual you were hosting in the Win32 window. For more information, see Tutorial: Hosting Visual Objects in a Win32 Application.

Upvotes: 1

Ian Oakes
Ian Oakes

Reputation: 10253

FindName won't work becuase the Canvas exists in the namescope of the UserControl, try using the LogicalTreeHelper instead.

 var canvas = LogicalTreeHelper.FindLogicalNode(
      Application.Current.MainWindow, "ChoiceCanvas") as Canvas; 

Upvotes: 1

Jeremiah Morrill
Jeremiah Morrill

Reputation: 4268

There is no RootVisual property in WPF. As far as I understand, the "Window" is the "root". You can get the Window that any WPF (D.O.) object belongs to by running the static method Window myWindow = Window.GetWindow(myControl);

Upvotes: 10

Related Questions