c# - How do I project models into viewmodels in XAML? -


given following classes:

public class neighborhood {     public ienumerable<house> houses { get; set; } }  public class house {     public address address { get; set; }     public ienumerable<room> rooms { get; set; } }  public class room {     public ienumerable<furniture> furniture { get; set; } } 

i want views this:

<!-- want datacontext neighborhoodviewmodel, not neighborhood --> <neighborhoodview>     <listbox itemssource={binding houses}/>     <button content="add house"/>     <button content="remove house"/> </neighborhoodview>  <!-- want datacontext houseviewmodel, not house--> <houseview>     <textbox text={binding address}/>      <listbox itemssource={binding rooms}/>     <button content="add room"/>     <button content="remove room"/> </houseview>  <!-- want datacontext roomviewmodel, not room --> <roomview>     <listbox itemssource={binding furniture}/>     <button content="add furniture"/>     <button content="remove furniture"/> </roomview> 

however, don't want neighborhoodviewmodel contain houseviewmodels. rather, should like:

public class neighborhoodviewmodel {     public ienumerable<room> rooms { get; }     public icommand addhousecommand { get; }     public icommand removehousecommand { get; } } 

how can declare bindings models in xaml, have bindings transformed viewmodels?

there 2 general ways can create type of effect. first way create static view , put datacontext behind each view. not mvvm views generated viewmodel bindings work. example of view.

<grid>     <houseview x:name="myhouse">      </houseview> </grid> 

in code behind can access houseview , set data context

public mainwindow() {     myhouse.datacontext = new myhouseviewmodel(); } 

this bindings work each 1 of these controls.

i not best practice of wpf , not way develop large projects. quick , dirty coding in opinion. can find out more on how proper mvvm style of coding here.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -