我想,我的问题相对简单。我有一个页面来显示我的数据。单击一个按钮,我想打开一个新页面,其中一个元素的datacontext在当前元素的datacontext之上2层。
解释:
我的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
}
我可以在其中按下按钮的视图绑定到SummaryViewModel的ObservableCollection的值。到现在为止一切都很好。当我按下按钮时,应该会打开一个显示详细信息的新页面。我使用ICommand来处理单击,并将其作为CommandParameter传递给详细视图。
<Button Name="OpenDetailsButton" Command="{Binding Path=ACommand}" CommandParameter="{DynamicResource Details}"
我将页面定义为同一文件中的资源,其中的datacontext仍然是ViewModelContainer。
<pages:DetailsViewPage DataContext="{Binding Path=det }" x:Key="Details"/>
页面打开,但datacontext不可用。我得到以下错误:
System.Windows.Data Error: 3 : Cannot find element that provides DataContext.
有谁知道如何打开详细信息视图并提供数据上下文吗?我不能将DetailsViewModel移动到另一个类,因为它只能在那里更新它。
谢谢
发布于 2012-11-17 23:48:36
我已经解决了这个问题,我创建了一个帮助器,让它沿着可视化树向上移动,并使用我需要的元素的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是您正在寻找的对象,例如窗口或按钮或其他东西。
发布于 2012-11-18 20:10:10
通常,视图和视图模型具有一对一的关系。在这种情况下,似乎存在一种多对一的关系。DetailsPageViewModel怎么样?
https://stackoverflow.com/questions/13433726
复制