Setting DataContext in code and XAML
-
I have a window with several bound items. Initially I set the DataContext in xaml like this:
<Window.DataContext> <local:UserManagerViewModel /> </Window.DataContext>
Everything is fine. The problem is I want to have the same ViewModel accessible to more than one window without instantiating more than one copy of the view model. So I want to set the
DataContext
in code to the one-and-only view model. Therefore I want to specify theDataContext
differently in xaml so that it knows what class the data will be without instantiating the view model. I don't know the right way to do this. Please help.Phil
The opinions expressed in this post are not necessarily those of the author, especially if you find them impolite, inaccurate or inflammatory.
-
I have a window with several bound items. Initially I set the DataContext in xaml like this:
<Window.DataContext> <local:UserManagerViewModel /> </Window.DataContext>
Everything is fine. The problem is I want to have the same ViewModel accessible to more than one window without instantiating more than one copy of the view model. So I want to set the
DataContext
in code to the one-and-only view model. Therefore I want to specify theDataContext
differently in xaml so that it knows what class the data will be without instantiating the view model. I don't know the right way to do this. Please help.Phil
The opinions expressed in this post are not necessarily those of the author, especially if you find them impolite, inaccurate or inflammatory.
If you really only ever have one instance of the view model You have two options: make
UserManagerViewModel
static, or turn it into a Singleton http://www.yoda.arachsys.com/csharp/singleton.html[^] Another strategy would be to create the object as a resource (possibly in the app.xaml) and refer child-windows to that.CCC solved so far: 2 (including a Hard One!) 37!?!! - Randall, Clerks