Abdullah Abdullah - 2 months ago 11
C# Question

How to Convert XAML File (View) into DependencyObject?

I am working on a project where i have to deal with navigation based on Frame in MVVM pattern thus to get to the element Name x:Name of type Frame we have to convert MainWindow into DependencyObject like this..

private static FrameworkElement GetDescendantFromName(DependencyObject parent, string name)
{
var count = VisualTreeHelper.GetChildrenCount(parent);

if (count < 1)
{
return null;
}

for (var i = 0; i < count; i++)
{
var frameworkElement = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (frameworkElement != null)
{
if (frameworkElement.Name == name)
{
return frameworkElement;
}

frameworkElement = GetDescendantFromName(frameworkElement, name);
if (frameworkElement != null)
{
return frameworkElement;
}
}
}
return null;
}


In Navigation Service Class i use...

var frame = GetDescendantFromName(Application.Current.MainWindow, "FrameName") as Frame;
frame.source = new Uri("Views/StudentView.Xaml");


This technique is limited to only MainWindow. How can i get same result on other Views such as EmployeeDetaiView.Xaml ? like

var frame = GetDescendantFromName(EmployeeDetaiView.Xaml, "FrameName") as Frame;

Answer

Use Application.LoadComponent Method (Uri)

Page p = (Page) Application.LoadComponent(new Uri("Views/EmployeeDetaiView.Xaml.xaml", UriKind.Relative));

var ctrl = GetDescendantFromName(p, "SomeControl");

Here, EmployeeDetaiView.Xaml lies in Views folder.