【问题标题】:How can I open a page and assign its datacontext如何打开页面并分配其数据上下文
【发布时间】:2012-11-17 18:57:11
【问题描述】:

我想我的问题相对简单。 我有一个页面来显示我的数据。单击按钮时,我想打开一个新页面,其中包含比当前元素的数据上下文高 2 层的元素的数据上下文。

解释:

我的 ViewModel 是一个包含更多 ViewModel 的类 (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
}

我可以按下按钮的视图绑定到 SummaryViewModel 的 ObservableCollection 的值。 到目前为止一切都很好。当我按下按钮时,应该打开一个显示详细信息的新页面。我使用 ICommand 来处理点击,并将详细信息视图作为 CommandParameter 传递给它。

<Button Name="OpenDetailsButton" Command="{Binding Path=ACommand}" CommandParameter="{DynamicResource Details}"

我将页面定义为同一文件中的资源,其中数据上下文仍然是 ViewModelContainer。

<pages:DetailsViewPage DataContext="{Binding Path=det }"  x:Key="Details"/>

页面打开,但数据上下文不可用。我收到以下错误:

  System.Windows.Data Error: 3 : Cannot find element that provides DataContext.

有人知道如何打开详细信息视图并提供数据上下文吗?我无法将 DetailsViewModel 移动到另一个类,因为只能在那里更新它。

谢谢

【问题讨论】:

    标签: c# wpf datacontext


    【解决方案1】:

    我通过创建一个帮助程序来向上可视化树并使用我需要的元素的数据上下文解决了这个问题。感谢所有试图提供帮助的人:)

    方法如下:

        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 是您要查找的对象,例如一个窗口或一个按钮或其他东西。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2022-11-12
        • 2010-11-17
        • 2011-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-29
        • 2014-02-19
        • 1970-01-01
        相关资源
        最近更新 更多