我有一个窗口,我想绑定来自2个不同DataModel的数据上下文。我遇到过这篇文章: WPF binding multiple controls to different datacontexts并且它在我的代码中无效。我不知道你是否必须设置一个类的“新”实例才能使它工作,但我不能让它显示我的数据。这是一个样本
<Grid>
<Button Command="{Binding FurnaceDataViewModel.StartButtonCommand}"/>
<Button Command="{Binding FurnaceDataViewModel.StopButtonCommand}"/>
<Button Command="{Binding FurnaceDataViewModel.ClearButtonCommand}"/>
<Label Content="{Binding FurnaceDataModel.TotalTimeIdle}" />
<Label Content="{Binding FurnaceDataModel.GallonsUsed}" />
<Label Content="{Binding FurnaceDataModel.TotalMoney}" />
<Label Content="{Binding FurnaceDataModel.TotalTimeRun}" />
</Grid>
我有我的MainWindow课程:
FurnaceDataContext dataContext = new FurnaceDataContext();
InitializeComponent();
DataContext = dataContext;
这是我的DataContext类
class FurnaceDataContext
{
public FurnaceDataViewModel FurnaceDataViewModel { get; set; }
public FurnaceDataModel FurnaceDataModel { get; set; }
public SqlDataModel SqlDataModel { get; set; }
}
我无法正确显示文本或按钮命令。任何想法?
答案 0 :(得分:5)
你需要实例化内部道具......
FurnaceDataContext dataContext = new FurnaceDataContext();
dataContext.FurnaceDataViewModel = new FurnaceDataViewModel();
dataContext.FurnaceDataModel = new FurnaceDataModel();
DataContext = dataContext;