c# - How to modifying a bound ObservableCollection from a UserControl, if the DataContext comes from the hosting window? -


using wpf, mvvm. have control, modifyzoocontrol, usercontrol. control because want add multiple windows.

one of windows modifyzoowindow, gets datacontext mvvmlight. add user control in window's xaml:

<uc:modifyzoocontrol/> 

the modifyzoocontrol has this, listing zoo instance's observablecollection<animal> animals property:

    <listbox name="animals" itemssource="{binding animals}">         <listbox.itemtemplate>             <datatemplate>                 <label content="{binding path=name}"/>             </datatemplate>         </listbox.itemtemplate>     </listbox> 

this works far, have window, , inside of modifyzoocontrol listing animals.

next, want modify list of animals control's codebehind. how do that?

animals.items.add(newanimal) doesn't work, because of "operation not valid while itemssource in use. access , modify elements itemscontrol.itemssource instead".

how reach original viewmodel animals observablecollection usercontrol's codebehind?

as understand 1 choice add 2 properties observablecollections usercontrol. , set values when instantiating usercontrol window. have references original observablecollections, , modify them. needed, considering there kind of reference collections through window's datacontext...?

also, usercontrol right choice kind of thing? should use frame rather, or else?

how reach original viewmodel animals observablecollection usercontrol's codebehind?

you typically not this. in general, it's typically better approach bind "command" that's requiring command, logic can remain in viewmodel. viewmodel should 1 adding new animal instance it's own collection.

if must reason, cast data context:

// in code behind: zoo vm = this.datacontext zoo; if (vm != null) {     observablecollection<animal> items = vm.animals;     items.add(newanimal); } 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -