[英]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..我正在处理一个项目,我必须在 MVVM 模式中处理基于 Frame 的导航,从而获得元素 Name x:Name 类型 Frame 我们必须像这样将 MainWindow 转换为 DependencyObject ..
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.此技术仅限于 MainWindow。 When i pass new instence of EmployeeDetailView.Xaml as a depenecy Object, The Xaml File is not loaded and GetChildrenCount() returns 0.
当我将 EmployeeDetailView.Xaml 的新实例作为依赖对象传递时,Xaml 文件未加载并且 GetChildrenCount() 返回 0。
var frame = GetDescendantFromName(EmployeeDetaiView.Xaml, "FrameName") as Frame;
here frame has null value.这里框架具有空值。 how could i make it work with currently rendered EmployeeDetailView to get the Frame element?
我怎样才能让它与当前呈现的 EmployeeDetailView 一起工作来获取 Frame 元素?
Use Application.LoadComponent Method (Uri)使用Application.LoadComponent 方法 (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.在这里,
EmployeeDetaiView.Xaml
位于 Views 文件夹中。
EDIT #1 after user comments在用户评论后编辑 #1
However, as pointed by OP in his comment that VisualTreeHelper.GetChildrenCount()
is returning 0. This happens because p
is not part of VisualTree
, once it is part of VisualTree
it will work correctly.然而,正如 OP 在他的评论中指出的,
VisualTreeHelper.GetChildrenCount()
返回 0。发生这种情况是因为p
不是VisualTree
一部分,一旦它成为VisualTree
一部分,它将正常工作。
Page p;
private void Button_Click_1(object sender, RoutedEventArgs e)
{
p = (Page) Application.LoadComponent(new Uri("Views/EmployeeDetaiView.Xaml.xaml", UriKind.Relative));
Frm.Content = p;
// This will print 0
int i = VisualTreeHelper.GetChildrenCount(p);
System.Diagnostics.Debug.WriteLine("Children count = " + i);
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
// Now it will correctly print 1, as 'p' is now part of VisualTree
int i = VisualTreeHelper.GetChildrenCount(p);
System.Diagnostics.Debug.WriteLine("Children count = " + i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.