Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/370.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何打开页面并分配其datacontext_C#_Wpf_Datacontext - Fatal编程技术网

C# 如何打开页面并分配其datacontext

C# 如何打开页面并分配其datacontext,c#,wpf,datacontext,C#,Wpf,Datacontext,我想我的问题相对简单。 我有一个页面来显示我的数据。单击一个按钮,我想打开一个新页面,其中元素的datacontext在当前元素的datacontext之上2层 说明: My ViewModel是一个包含更多ViewModels的类(ViewModelContainer)。一个是值的摘要,另一个是值的详细视图 public class SummaryViewModel { public int somevalue; // is a property public Observ

我想我的问题相对简单。 我有一个页面来显示我的数据。单击一个按钮,我想打开一个新页面,其中元素的datacontext在当前元素的datacontext之上2层

说明:

My ViewModel是一个包含更多ViewModels的类(ViewModelContainer)。一个是值的摘要,另一个是值的详细视图

public class SummaryViewModel
{
     public int somevalue; // is a property
     public ObservableCollection<SummarizedItems> items; // is a property
}

public class DetailsViewModel
{
     public int someOthervalue; // is a property
     public int stuffA; // is a property
     public int stuffB; // is a property
}

public class ViewModelContainer : ViewModelBase
{
     private SummaryViewModel _sum;
     public SummaryViewModel sum { }  // is a property

     private DetailsViewModel _det;
     public DetailsViewModel det { }  // is a property
}
有人知道我如何打开details视图并提供datacontext吗?我无法将DetailsViewModel移动到另一个类,因为只能在那里更新它


谢谢

我已经解决了这个问题,我创建了一个帮助器,可以进入可视化树并使用我需要的元素的datacontext。感谢所有试图帮助的人:)

方法如下所示:

    public static UIELEMENT FindUiElementUpVisualTree(DependencyObject initial)
    {
        DependencyObject current = initial;

        while (current != null && current.GetType() != typeof(UIELEMENT))
        {
            current = VisualTreeHelper.GetParent(current);
        }
        return current as UIELEMENT;
    }

其中UIELEMENT是您要查找的对象,例如窗口、按钮等。

通常视图和视图模型具有一对一的关系。在这种情况下,似乎存在多对一的关系。一个DetailsPageViewModel怎么样

<pages:DetailsViewPage DataContext="{Binding Path=det }"  x:Key="Details"/>
  System.Windows.Data Error: 3 : Cannot find element that provides DataContext.
    public static UIELEMENT FindUiElementUpVisualTree(DependencyObject initial)
    {
        DependencyObject current = initial;

        while (current != null && current.GetType() != typeof(UIELEMENT))
        {
            current = VisualTreeHelper.GetParent(current);
        }
        return current as UIELEMENT;
    }