简体   繁体   中英

Multiple DataContext in wpf MVVM?

i have a window that i'd like to bind the data context from 2 different DataModels from. i've come across this post: WPF binding multiple controls to different datacontexts and it's not working in my code. i don't know if you have to set a 'new' instance of the classes to make it work, but i can't get it to show my data. here's a sample

<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>

i have my MainWindow Class:

FurnaceDataContext dataContext = new FurnaceDataContext();
InitializeComponent();
DataContext = dataContext;

here's my DataContext class

class FurnaceDataContext
{
    public FurnaceDataViewModel FurnaceDataViewModel { get; set; }
    public FurnaceDataModel FurnaceDataModel { get; set; }
    public SqlDataModel SqlDataModel { get; set; }
}

i can't get it to display my text correctly or my button commands. any ideas?

You need to instantiate inner props....

    FurnaceDataContext dataContext = new FurnaceDataContext();

    dataContext.FurnaceDataViewModel  = new FurnaceDataViewModel();
    dataContext.FurnaceDataModel = new FurnaceDataModel();

    DataContext = dataContext;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM