如何将XAML文件(View)转换为DependencyObject?

时间:2016-09-20 16:18:24

标签: c# wpf xaml mvvm

我正在开发一个项目,我必须处理基于MVVM模式的框架的导航,从而获得元素名称x:类型的名称框架我们必须将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;
        }

在导航服务类我使用...

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

此技术仅限于MainWindow。当我将EmployeeDetailView.Xaml的新内容作为依赖性对象传递时,未加载Xaml文件并且GetChildrenCount()返回0.

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

此处框架具有 null 值。 我怎么能使它与当前渲染的EmployeeDetailView一起使用以获取Frame元素?

1 个答案:

答案 0 :(得分:-1)

使用Application.LoadComponent Method (Uri)

$scope.my_tree_handler = function (branch) {
    branch.style.color = "red"; // "branch" is an object by the way
};

此处,Page p = (Page) Application.LoadComponent(new Uri("Views/EmployeeDetaiView.Xaml.xaml", UriKind.Relative)); var ctrl = GetDescendantFromName(p, "SomeControl"); 位于Views文件夹中。

用户评论后编辑#1

然而,正如OP在他的评论中所指出的那样EmployeeDetaiView.Xaml正在返回0.这是因为VisualTreeHelper.GetChildrenCount()不属于p,一旦属于VisualTree它会正常工作。

VisualTree