Dependency Injection + MVVM?
I followed a Tim Corey tutorial on Dependency Injection in WPF but he did not use MVVM just raw code behind. How hard would be to switch over to MVVM? I just want an app where I have a MainView, SettingsView, and a few other Views. He uses Interfaces, etc and I'm lost. :<
What should I do?
247 Replies
I hate confusion, bad enough MVVM can be confusing sometimes for me lol
IMO switching to MVVM just for the sake of it on a small app would only be useful to learn. That said, if you already have DI, it shouldn't be that hard to do
i know mvvm but i dunno how to impliment tim corey's di
as it's bad practice what he did apparently :/
maybe i will just do the MVVM part
and post my code later if someone wants to help me with the DI part XD
i cant fiddle with unknowns when i need to make something fast
its why i keep going to winforms, it just works :x
IAmTimCorey
YouTube
Dependency Injection in WPF in .NET 6 Including the Factory Pattern
.NET Core has a built-in dependency injection that we use in every web project type we create. However, did you know that you can also use that same dependency injection in the .NET Core version of WPF? In this video, we are going to enable dependency injection in WPF and then use it for some common scenarios, including creating multiple forms.
...
i used his DI setup but its for non-mvvm
i know some mvvm but iam not good at combining ideas into 1, autism sucks 😦
so i always get stuck with concepts
I added the common Models, ViewModels, Views folder
added CommunityToolkit.MVVM as well etc
so i got that far 😄
push to github
and post link 😉
wheee
i gotta make a new ssh, sec
pushing
https://github.com/coredreamstudios/TitanSTUDIO
yay 😄
ignore the MainView.xaml window, i renamed the original to MainViewDI.xaml so i can work on my UI while i wait
u forgot to set it pub
i cant keep it private?
sec
if u keep it private then u have to invite people in order for them to see it
done
leowest77
its now public
In the toolkit MVVM samples they have basically what you're looking for
https://github.com/CommunityToolkit/MVVM-Samples/blob/master/samples/MvvmSampleUwp/App.xaml.cs#L56
GitHub
MVVM-Samples/samples/MvvmSampleUwp/App.xaml.cs at master · Communit...
Sample repo for MVVM package. Contribute to CommunityToolkit/MVVM-Samples development by creating an account on GitHub.
They add the viewmodels as transient in the container, the views can then either: be added to the container, or get the view model from the container
it uses UWP but the same applies for WPF
@Core Dream Studios a lot of the things u have in your viewdi, will go in the viewmodel
or are the 2 different windows?
minus the _click's of course as we will use ICommand's right?
some of the ui events would become commands yes
not sure why tim made child forms like that
but imagine for example if u wanted to load something when the window loads
you cant customize em as they're all the same XD
then what we often do is we wire it from the view to the vm
yep, that i understand
do i even need factories? i dont even know wth those even are XD
i only did what he did
u may use factories in some scenarios but for a simple app at the level u are right now u shouldn't have to worry about it
all u have are either singleton or scoped stuff
my app is very simple, all it will do is write/read files, and ram addresses, nothing special
no web, etc
its worth learning about the lifecycle of things
so u understand which one u should use
singleton i know means a window/form which you use once, aka the main one
that i get
the transient means more than 1 use
according to what tim said
singleton will live trhu the entire duration of the app
im gonna try to update my code to reflect the DI with MVVM then push changes to github
yes, aka main window 🙂
also u added CTK but you're not using it u still have INPC stuff
CTK?
CommunityToolkit abbrev
yeah i didnt switch over yet
was doing some raw basic stuff for now
but gonna switch in a minute
i will update my github in 20min
its ok im just going thru what is in there for now and seeing what changes are required to plug mvvm with di
that code behind Tim did with the Main .xaml, thats bad practice for mvvm for sure
yes because it mix view with things that aren't view
i think datacontext would be best here
DataContext would still live in the view
althou u can also set it via di initialization
the concept of DI is
you have an object with a dependency
when that object is initialize DI will query its setvices and see if it have an instance it can fullfil that dependency
so it looks up oh I have a singleton MainViewModel, let me pass it via that constructor
i will see how far i can get now, will update github when done 🙂
i guess i iwll delete this
as its not mvvm
that is
oh
part of it at least
I will update u in a bit
ok
i dont understand why he did child view/forms like he did
since you cant modify them individually XD
like ui etc
well I did not watch his video he must have a reason
but it all depends how the childs will be used
but i dont want a cookie cutter child form
each window will have its own look tbh for me
aka SettingsView
also u realize button have a control called Content
where u can write Button 2 instead of wrapping a textblock right?
oh, yeah , i know, im doing it in a rush so i can focus on the mvvm/di first
well normally wpf is not designed to have multiple windows like winforms u can
i also need to do templating which is not needed right now
but usually you have a navigation using usercontrols
that swap to different locations
so wouldnt i use pages then?
with that one window u have
err user controls
UserControls is fine
I dont ever recall ever using Pages with WPF
maybe once to explain it to some one about the navigation system they have in the docs
but that was it
pages is more of a ASP.NET / Blazor thing im sure
but yes i can do Main and UC
and use the child style he did
welp i got a lot to work on before i can upload a updated code base
so probably wont be for a hour or more XD
now with user controls
those also will need viewmodels right?
based on what they will do each
SettingsUserControlViewModel etc?
some will yes
u dont need to append UserControl to the name
ok
just SettingView/ViewModel
ty
I will update here when i got something useful to show
thank you @leowest 🙂
np
another thing is that ur not using binding at all
yeah i know
I assume because u were copying Tim's stuff
i was doing raw
im switchingt to mvvm now yes 🙂
MVVM = ❤️
so ChildView becomes UserControl from Window
via xaml I added a 3rd grid where I have a ControlControl to show the childview inside
ControlControl?
oh
the datatemplate defines the vm for the childview do I dont need to wire anything on the View of Child
DI will do it all by it self
the buttons werent meant to be on top tbh
i was gonna do something gamified
it doesn't matter its just to show how it all wires nad works its fine
oh ok
i should of kept the overrides?
i removed them
(not focused on child atm its why I commented it out)
its ok u do u
im just showing what u have wired
what it would could look like
well now my window wont even load
so that contentcontrol I showed u above
I can easily add more templates to it of different childs
so i probably will need the overrides on OnStartup etcc
and swap it via the vm
thats fair
Child is what is bound to the contentcontrol
i removed the startupwindow
as tim said to do
yes u have to
since u wire it from the app.xaml.cs
ok but how to i load it now? i removed the OnStartup/OnExit
oh ok, so same way
got it
so many variables 😂
yeah what is in the app.xaml.cs is basic setup for the di
it doesnt really change much
im gonna make a base template out of this project
im sure i can save it as a Project Template
yay
<StatusBar Grid.Row="1" Background="#222" Foreground="WhiteSmoke">
<StatusBarItem Margin="20 5" Content="{Binding Version}"/>
<StatusBarItem Margin="20 5" Content="Item 2"/>
<StatusBarItem Margin="20 5" Content="Item 3"/>
</StatusBar>
and bind works 🙂
I think I'm getting somewhere
( I didn't do templating, its why you see margin repeating 😄 )
So... Interfaces, is basically like how C++ has header files?
you have the main class then a interface which refers to the methods?
I will just read the msdn docs on those
no
interfaces are like contracts
c++ often split the signature in a header file and the method in the cpp file
i.e.:
signature
to illustrate what I was saying earlier
I can easily swap between child a and b
where button 1 is accessing your data
as long as each child, has its own uI
since im gonna many, one for settings with comboboxes, buttons, textboxes etc. and others with similar but for other roles
if you have a UserControl you could just add it to your xaml using say
this would make so it inherits the datacontext from the parent, so if the parent was MainViewModel, it inherits it.
however if u define a DataTemplate with a specific ViewModel
it will be given that
ok
the datatemplate is also what allows u to use the BaseViewModel as a type to render the View
instead of having to use the View and wire everything
Getting overwhelmed but trying
well I will just leave u to it once u finish doing your thing and update let me know and I will take a look again
thank you, def getting somewhere 🙂
almost got it going XD
i can't get this to work with UserControls so far
its ok do the rest first
get the rest working
and then u can go into that
oh, was trying to load up the usercontrol i made XD
hrm
my code didn't update on the github XD
im getting sloppy 😦
did u forget to set the upstream or something
check what origin/master are set to
its not letting me push i think
even though i told it too
if i switch to origin/master on remote and try
i get this
did u commit and then push
also that is not what I meant by check master/origin
check what its set to sometimes its set to local
so it may not be pushing to github
that doesnt tell u what master is set to
where am i not looking?
git remote show origin
for example
ok
F:\Backups\Backup-DevDrive\source\csharp\wpf\TitanSTUDIO>git remote show origin
'git' is not recognized as an internal or external command,
operable program or batch file.
ugh im getting stupid, timeout for tonight i guess
:catlaugh:
i will install git
looks like u dont have git installed outside the dev env or something
yeah, i hardly used it til now, i will install
sometimes its easier to get the info via cli
u have a typo
ah nvm u fixed after
git push origin master:master
GitHub
TitanSTUDIO/TitanSTUDIO/App.xaml.cs at master · coredreamstudios/Ti...
Contribute to coredreamstudios/TitanSTUDIO development by creating an account on GitHub.
no change
yeah I dunno it looks fine visually
maybe zip it to save the changes and try to git push origin
I assume those changes u showed in the window were commited right
git commit -m "Additional changes"
if they were this could should say there is no changes or w/e
let me do this, brb
ah u didnt set that up on visual studio
not surprised 😂
we good now
GitHub
TitanSTUDIO/TitanSTUDIO at master · coredreamstudios/TitanSTUDIO
Contribute to coredreamstudios/TitanSTUDIO development by creating an account on GitHub.
u dont need to do
that was just for testing
u can just do
less boilerplate
ah
it generates all the rest for u
i got the old fashioned way stuck in my head
XD
isnt human memory fun? 😊
this is a view
but its a UC?
confusing
yes it is confusing
but you're using that one as a view
i want it to be a uc
so its in the mainview window
when you're create a UserControl for the purpose of it being just a control that is a different thing
user controls are views
it will be a child in the mainwindow for settings
where u want its own vm
uis are called views
see, i hate layout 😦
just think of it as Features
i dunno if i want settings as a self contained uc or a window
forget View and ViewModel
imagine this
maybe im using UserControls for the wrong reasons
as UC is to make CUSTOM control
i get it now
so i must use a window as a view 🙂
no
nice tree
window is always the shell
ok
its the top level where u can house views
ok so MainView.xaml is fine
I usually name it Shell to make it less complciated but sure u can name it MainWindowView MainView
it all makes sense
some people make different ways of doing things
example, this app, also WPF
using popup windows
so its confusing 😦
u can have Dialog Popup as a window
that is no problem
what would this be called
you would have a dialogservice
that would summon that window
etc
i am horrible with design, its not something im good at
honestly that would be similar a toolwindow
i can ironically make logos, illustrations etc
but not ui
these are just window/view concepts
but have u stopped to think u may not new a separted window?
maybe your window is alredy big enough that simple having a navigation with in it
is enough to house the settings page
Honestly I think of the whole layout like this
Shell/Window/Main as the casket
all other UserControls are Views that are housed by it or summoned by it in some fashion
ok so i got rid of the UserControls folder
and made a Settings Window named SettingsView
if i was rich id just hire someone to do the ui
but im on ssi trying to make a life for myself and failing (perm physical disability)
im very close too :X
so you're set that ur settingsview must be a window on its own
then u will need to write a service that u will inject to your vm that needs to call it that will open/close/manage it
well it dont need to be its own window
it could be embedded
well u create it as Window
hell, do it as a tab
so it can only be a window
so what do I use?
back to usercontrols?
if u want it to be housed inside a window it needs to be a UserControl
ok got it
ok there
makes sense since embedded wont have its own modal buttons and title
yep
now u make a vm for it and wire it all in the di and datatemplate
and that's it
all set
u dont need that
u just need the datatemplate
leowest
Quoted by
<@626236623104770049> from #Dependency Injection + MVVM? (click here)
React with ❌ to remove this embed.
this?
yes
ok, sorry
and each view/vm would be 1 separate datatemplate of the views u want to be able to be swapped in there
u can also connect the selection there to what was selected in a listbox if u want to make the menu react when u select something
im close
well your settingsview is not called childview
yep fixed
did u do the binding on the vm
for Child
i dont even have nothing to bind yet, settingsview is emoty
u do
u need to setup that if u want it to actually display
so do i make dummy data pretty much in the vm?
mmm no
using CommunityToolkit.Mvvm.ComponentModel;
namespace TitanSTUDIO.ViewModels;
public partial class SettingsViewModel : ObservableObject
{
[ObservableProperty]
private string _dummy = "Dummy Data";
}
oh 😐
👆
child sample there
ok so what is this BaseViewModel
i dont even see code for it
im getting too tired and making dumbass mistakes tbh
ah its just the ObservableObject but instead I made a class that inherits from it as I tend to have things like Name and other properties that are common between
ok
changed it back to ObservableObject
what is this going to be used for?
just an example
its also a common class to be used if u need to have a List of VM or something
but this is getting too confusing now
or an object that can be different vms
so many addons :/
imagine this
how would u be able to have SettingsViewModel, HomeViewModel, LoginViewModel inside Child
is they have nothing in common
ok
BaseViewModel acts as the interpreter for that
thats true
so its like the glue between them all
I will be back in 30 minutes or so food
i need to sleep tbh, its past my bed time XD
its why im messing up
i cant focus
but there, a basemodel
and some error i guess
but no problem, have a good one 🙂
now u need SettingsViewModel to inherit from it
every vm would inherit from BaseViewModel
that does make more sense
😛
it should build/run now
now it can access both baseviewmodel and the data in there
ok sec
I dont see the last error
getting somewhere
what time is it by you?
u have not made the Child property
to set it to the settings
so its just inheriting CHild from the MainViewModel
and printing it
11
yeah ill fix it in a bit
its 10pm for me sadly
11am?
pm
ah
you on tomorrow night at all? i cant function when my head is burnt out tbh
never code when tired 🙂
¯\_(ツ)_/¯
im usually around
<ContentControl Grid.Row="0" Content="{Binding }">
<ContentControl.Resources>
<DataTemplate DataType="{x:Type vm:SettingsViewModel}">
<local:SettingsView />
</DataTemplate>
</ContentControl.Resources>
</ContentControl>
i just need to figurew out what to bind to
ok np
i will def get back to this tomorrow, it's useless to do this if i can't focus
done that so many times too, doesn't help XD
I appreciate your help though @leowest , learning alot tbh.