How to Close Windows from a ViewModel in C#

  Рет қаралды 25,765

Brian Lagunas

Brian Lagunas

Күн бұрын

Пікірлер: 200
@freemax32
@freemax32 3 жыл бұрын
That feeling when there is a specific task and you have found a solution!
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Woot woot! I'm glad this video was helpful
@faisletoismeme
@faisletoismeme 2 жыл бұрын
Man you blow my mind. I'm learning so many new concepts and techniques... you are an amazing teacher and you definitely know your stuff. Thanks for the immense help.
@BrianLagunas
@BrianLagunas 2 жыл бұрын
Thank you so much for the kind words
@rosscarlson3701
@rosscarlson3701 2 жыл бұрын
This is cleaner, less-coupled method than what I've been using ... I'm going to switch to this. Thanks!
@BrianLagunas
@BrianLagunas 2 жыл бұрын
Thanks for watching
@MudasarRauf
@MudasarRauf 4 жыл бұрын
thank you @Brian Finally i understand how and when to use attached properties along with the the window closing :-)
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Great! I'm glad I could help.
@noaml-1
@noaml-1 4 жыл бұрын
Hi Brian, it would be great if you add this feature to Prism.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
This feature already exists in Prism when you use the IDialogService 😀
@mehransarrafi7790
@mehransarrafi7790 2 жыл бұрын
Hello and thanks for your tutorial. I couldn't run the program, because I have a question. What's that DelegateCommand and where is it implemented? Thanks in advance.
@BrianLagunas
@BrianLagunas 2 жыл бұрын
DelegateCommand is an ICommand implementation that allows you to provide delegates in-place of the Execute and CanExecute. You get it from the Prism.Core NuGet package. You can learn more about it here prismlibrary.com/docs/commanding.html#creating-a-delegatecommand
@barti890300
@barti890300 3 жыл бұрын
Works Perfect, I have question though, How does "Close" Action "know" to use WindowCloser class? I mean where is the reference from ViewModel class to WindowCloser?
@manuelballesteros79
@manuelballesteros79 3 жыл бұрын
@Brian Lagunas Thank you very much for your videos and courses, they are all excellent! I just wanted to ask you something that is still not clear to me. That is, If the goal is to NOT instantiate a UI-Element in the VM, then why in the OnEnableWindowClosingChanged method in the VM you are instantiating a Window in the line 52: if (d is Window window) ?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
The attached property is defined in a new class called WindowCloser and NOT in the VM.
@TheCodeVicious
@TheCodeVicious 3 жыл бұрын
Hi Brian, Thanks for the amazing (as always) best practice. Suppose I have to close the window from an MVVM of a UserControl in a Region (Prism) say the "Footer", could I use the EventAggregator to "send the closing message" to the MVVM of the MainWindow? Or is there a better way?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
You can always get the parent window of a user control if you need it
@essamsalah829
@essamsalah829 4 жыл бұрын
hi Brian, thank you for sharing this wpf good practices, I have a question, since I'm newbie to mvvm why it's not good practice to reference the View from ViewModel? I know it's for separation of concerns but I can't feel it maybe because I haven't built a big wpf project yet, but is there other reasons for Not to reference the view in vm. thanks again
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Referencing a view object in a VM is the worst thing you can do. It creates a tight coupling between your view and VM, which not only breaks a number of other design patterns, but severely limits your ability to unit test anything. My question to you would be, if you are reference the view in your VM, why even have a VM. You might as well just use code-behind.
@taab84
@taab84 4 жыл бұрын
This approach will work if instean we try to print Ui content element (like datagrid)?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Sure, give it a try
@hussainhussaini2267
@hussainhussaini2267 3 жыл бұрын
Very helpful. Can you please also make a video on how to open a new window from the viewmodel?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Thanks for the suggestion. I'll add it to my list.
@hussainhussaini2267
@hussainhussaini2267 3 жыл бұрын
@@BrianLagunas Waiting for that impatiently!!!
@franckespinosa5776
@franckespinosa5776 3 жыл бұрын
@@BrianLagunas Is this still on your radar?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Yes it is
@DirkStoermer
@DirkStoermer Жыл бұрын
Cool, nice approach. That's exactly what I was looking for. Many thanks.
@BrianLagunas
@BrianLagunas Жыл бұрын
You’re welcome
@mywildlifestories3793
@mywildlifestories3793 4 жыл бұрын
Hey Brian, how do we identify the performance issues in wpf app and what is best approach to resolve the same?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Start with the built in performance and profiling tools built into Visual Studio. Can also use other 3rd party tools you could use.
@tweshlyallpuri
@tweshlyallpuri 4 жыл бұрын
I am working on a prism app in which one of the modules is supposed to read an XML and display in a tree view control. Basically to store by database info and encrypted credentials and be able to access them from tree view. I was wondering if we could have a video regarding best XML practices and binding a strongly typed list or loosely typed xelement to Treeview. Thanks in advance. Your videos are amazing which prompted me to make the prism based wpf app for my personal usage.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Can you clarify what you mean? Are you storing XML in a database and want to parse that data into objects that you can bind in your WPF UI?
@tweshlyallpuri
@tweshlyallpuri 4 жыл бұрын
@@BrianLagunas Hey Thanks for your reply. I am storing Datasource info like Hostname,port,aliasname,credentials etc in an xaml file. And then binding that xml file to treeview so as to access the datasource information much more easily from the Wpf UI. Filtering/selecting the datasource from treeview and viewing all information in a stack panel besides maybe. Thanks. I can share the github link if you like (after a bit of tidying up of code ofcourse :))
@pickedupapencil
@pickedupapencil 4 жыл бұрын
So crazy. I came up with a solution very similar to this about a year ago using an interface and an attached behavior. Very nice, in my opinion.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
You definitely did it the right way my friend.
@VinuP2023
@VinuP2023 4 жыл бұрын
Thank you Sir 😊 Your tech questions series is going to be popular among all of us. Good to see straight to the point solution for the problem
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you very much. I will do my best
@douglasbates389
@douglasbates389 3 жыл бұрын
Excellent video Brian. I have a C# WPF MVVM problem for you if you have time. If I had a Nested TabControl similar to the following TabControlP TabItemP1 TabControlQ TabItemQ1 TabControlR TabItemR1 TabItemR2 TabItemR3 TabItemQ2 TabControlS TabItemS1 TabItemP2 TabControlT TabItemT1 TabControlU TabItemU1 where TabItemR1,TabItemR2, TabItemR3, TabItemS1 and TabItemU1 are the Leaf Items and they contain lets say 2 ComboBoxes each. What I would like to know is how can I control the TabItem HeaderTemplate Text and Background color when the ComboBoxes are executed. What I want to do is change the Text and Background Color of the TabItem Header Template in the following manner (Lets say each ComboBox contains the following entries "","Entry1","Entry2" for simplicity) Initially all TabItem HeaderTemplate Background Colors will be set to White. (1). If TabItemR1 is clicked and all of the ComboBoxes have null or empty selections then the Text and Background Color is changed to Yellow. (2). If TabItemR1 is clicked and only one ComboBox has a not null or empty selection then the Text and Background Color is changed to Red (3). If TabItemR1 is clicked and all ComboBoxes have not null or empty selections then the Text and Background Color is changed to Green If TabItemR1 HeaderTemplate Background Color is Red or Green then I want TabItemQ1 and TabItemP1 to have the same Color and Text (CasCade Up). The same rules apply to the other Leaf Items. What would the ViewModel look like using your rule of no code behind in the View.
@BrianLagunas
@BrianLagunas 3 жыл бұрын
I'm sorry, but I've read that like 4 times and still do not have a clear idea of the issue you are facing. I will say that the rule isn't no code behind ever. Be practical and only add code behind when necessary.
@douglasbates389
@douglasbates389 3 жыл бұрын
@@BrianLagunas Hi Brian, Thank you for replying to my comment. Sorry for not explaining the Nested TabControl problem better. I tried to show how the TabControls are related by doing an Indentation Tree. If you for example take one of the TabItems (say TabItemR1 which is a GrandChild of TabItemP1 and a Child of TabItemQ1) that contains two ComboBoxes. If I select a value from one of the ComboBoxes then I want the TabItem Header Background Colors of TabItemR1,TabItemQ1 and TabItemP1 to change to Red. If Both ComboBoxes in TabItemR1 have values selected then the TabItem Header Background Colors of TabItemR1,TabItemQ1 and TabItemP1 to change to Green. I can send you the code if you like.
@AbsurdKangaroo
@AbsurdKangaroo 4 жыл бұрын
Care to comment on how you would do it without Prism? Or is that not worth considering?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
This will work with or without Prism. It has no impact
@AbsurdKangaroo
@AbsurdKangaroo 4 жыл бұрын
@@BrianLagunas thanks! you mentioned “delegatecommand from Prism” so that threw me off.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Ahh yes, if not using DelegateCommand you'll use your own ICommand implementation
@harsheng
@harsheng 4 жыл бұрын
How to write unit test of these kind of things i mean to say if we are using any view components either through Action or dp?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Your tests would mock the view behavior. You would use the abstractions in your test code to execute the actions. There are usually no interactive UI components in unit tests.
@asdswx
@asdswx Жыл бұрын
Hello, thank you for video, but I have problem with WindowCloser with method private static void OnEnableWindowClosingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is Window window) { window.Loaded += (s, e) => { if (window.DataContext is ICloseWindow vm) { vm.Close += () => { window.Close(); }; window.Closing += (s, e) => { e.Cancel = !vm.CanClose(); }; } }; } } here I have error for s and e "conflicting variable defined below" also was same in MainWindow code behind, how can I repair, thank you
@solvedplus858
@solvedplus858 3 жыл бұрын
can you please show me how to open another window from main window and how to pass data between them in both ways? views & viewmodels different dll file another question, is using ImageSource as property type break MVVM pattern many thanks in advance
@BrianLagunas
@BrianLagunas 3 жыл бұрын
I plan on doing a video on creating a dialog service. Yes, using ImageSource breaks MVVM.
@solvedplus858
@solvedplus858 3 жыл бұрын
@@BrianLagunas many thanks for replay what can I use for image source instead of it , not to beak the MVVm I look also for example for more than dialog service, I hope you can learn us also how to get data from the other window specially list types many thanks in advance
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Just use a string with the image path. If you absolutely have an image Source, use a converter
@solvedplus858
@solvedplus858 3 жыл бұрын
@@BrianLagunas I get the image from clipboard while paste, or take snip from the screen
@tomroberts1216
@tomroberts1216 4 жыл бұрын
Thanks Brian. Very useful. Q: Would this change at all if you were to use the autoviewmodellocator? If so, what would change?
@tomroberts1216
@tomroberts1216 4 жыл бұрын
Just to put my question in context. You used Datacontext and autoviewmodellocator eliminates the need for the use of Datacontext.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@tomroberts1216 Nothing would change if you used AutowireViewModel. It works the same
@zeljkolazic2542
@zeljkolazic2542 3 жыл бұрын
if (DataContext is ICloseWindow vm)...error: vm does not exist in the current context. Does this only work using Prism?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
You might be using an older version of C# where this syntax isn't supported. You'll just have to use a different syntax.
@AbsurdKangaroo
@AbsurdKangaroo 4 жыл бұрын
I’m having trouble applying the attached property in xaml. I notice yours auto fills.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Hard to say without seeing the code. Make sure you have properly defined the attached property and build the project
@AbsurdKangaroo
@AbsurdKangaroo 4 жыл бұрын
@@BrianLagunas yep. For some reason clean and build the project fixed it. I updated VS and hopefully that won’t happen anymore. Thanks for all you do man!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Glad you figured it out. VS has been the root of a lot of my issues recently.
@wifixx
@wifixx 3 жыл бұрын
Having the same issue here, can't see a single thing when I enter "local:" in xaml. Can't even link my view model.
@bjorn1409
@bjorn1409 4 жыл бұрын
Hi Brian, great video, thanks a lot! I have tried to use your code in a PRISM application but it didn't work. I guess it has something to do with the way the dataContext is set because i use the AutowireViewModel=True (just a guess). How would the code look like closing the MainWindow with PRISM MVVM?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
You might want to hook into the DataContextChanged event and then hook into any events on the VM. Let me know if that works
@PinkyParu
@PinkyParu 4 жыл бұрын
am getting compile time error for using (s,e) already s is declared in the scope, as well as for e, how you are not getting ? I resolved by just giving different name
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Hmmm... hard to say. I'd have to see the code/environment to understand what may be causing the issue. As long as you got it to work, that's the important part 😁
@sem4461
@sem4461 3 жыл бұрын
I can't seem to figure out how to write unit tests for the attached property. Can someone help me with this? Do I just wrap the WindowCloser Class in an Interface and mock it or am I completely off?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
I don't usually try to unit test Window objects that show and close. If you wanted to do this, I think you have to create the window in a separate thread, configure the STA thread, and manage the dispatcher. What you would usually unit test is the VM that implements ICloseWindows and just call the close method directly to test the logic in the VM.
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Your unit test might look something like this: [Fact] public void VM_Closes_Window() { var vm = new MainWindowViewModel(); var didClose = false; vm.Close = () => { didClose = true; }; vm.CloseCommand.Execute(); Assert.True(didClose); }
@sem4461
@sem4461 3 жыл бұрын
@@BrianLagunas Thank you so much this worked. I hate when you're stuck on something for so long and it seems to be the simplest solution :)
@osman3404
@osman3404 4 жыл бұрын
If We put all viewmodel logic into its own project/dll whats a good way to compile-time, in-force not allowing reference to any UI elements in that project (or any c# file in that matter)
@BrianLagunas
@BrianLagunas 4 жыл бұрын
If you place your VM in another project, make that project a .NET Standard or even a .NET Core class library project. Then you won't be able.
@lukaszluczko
@lukaszluczko 4 жыл бұрын
@Brian How to open new window difrent than main window?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
You'll want to use some kind of service for that. Prism has a built-in dialog service for that. You'll want to do something similar. Maybe I should do a video on that.
@lukaszluczko
@lukaszluczko 4 жыл бұрын
@@BrianLagunas will be greate if You prepare video about that.
@cpmoliveira
@cpmoliveira 4 жыл бұрын
Hi Brian, thanks for helping us with these enlightening videos. Well, I'm a big fan of your work, especially on Prism. So I would like to request that you could present us a video with examples on the different methods of communication between the MVVM layers, and how/when to use them on Prism: Binding, Commanding, Shared Services, Event Aggregation, etc. I attended your course in Pluralsight, but I have doubts such as, for example, a View control communicates with the ViewModel and it responds by executing a method of another control in the View. Regards!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you for the kind words. Your question is actually very broad and would be difficult to create a short video on what is really multiple topics. Chances are I won't even answer the specific scenario you are trying to solve. Maybe if you could provide more detail on exactly what you are trying to do, that would help me better understand the scenario.
@cpmoliveira
@cpmoliveira 4 жыл бұрын
@@BrianLagunas As I am newbie to MVVM, I have many doubts! But I am trying to introduce an MVVM architecture to my team. We developed Decision Support Systems in Water Resources, with the use of GIS tools being very common. A simple example of something I'm trying to do is: 1) When clicking a button, a call must be made to a method in the GIS control that must load a file. Or, 2) When the mouse is moved over a map, the coordinates must be shown in realtime in a status bar. For simplicity, in both examples, the GIS control can be replaced by a PictureBox.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@cpmoliveira Your approach will depend on your app architecture. I'm not just talking about MVVM. I mean your overall app architecture.
@cpmoliveira
@cpmoliveira 4 жыл бұрын
@@BrianLagunas In time, I'm working on a WPF project with .NET 5 and Prism 8.
@taruntirkey
@taruntirkey 4 жыл бұрын
Hi Brian. Nice video. what is the best way to save a configuration securely in a WPF application? And is it different in WPF .Net Core?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Great question. Let me think about it
@Zonawanialonnua
@Zonawanialonnua 4 жыл бұрын
Hi Brian! You are a wonderful teacher! Thank!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you very much for the kind words
@habanerohoncho
@habanerohoncho 4 жыл бұрын
Thank you sir. Your stuff is golden. Audio-video sync looking/sounding good to me.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
So good to hear. I guess i will use this mic from now on. Thanks for letting me know.
@harvey6456
@harvey6456 2 жыл бұрын
I combine this demo with DialogService, thanks a lot.
@mrt7948
@mrt7948 2 жыл бұрын
that you very much, these kind of tips are really helpful for beginners like me.
@BrianLagunas
@BrianLagunas 2 жыл бұрын
Thanks for watching
@kasozivincent107
@kasozivincent107 4 жыл бұрын
Brian what if I gave the window a name and then attached a command on the button and pass in the window as a command parameter? I am a bit confused now coz it seems I am referencing a UI component in my view model 😏😏. Does this mean interactivity is lame? It seems it promotes this. Maybe I use it wrongly . Will be glad to hear your answer. Thanks
@BrianLagunas
@BrianLagunas 4 жыл бұрын
That is very bad. Never use UI elements in your VM. So, this means do not pass the window as a parameter to your command.
@kasozivincent107
@kasozivincent107 4 жыл бұрын
Brian trust me this video has left all my code broken 😹😹. I don’t know how many times I have referenced my UI in my code behind. Oh my hell has broken lose. It seems writing code can seem overkill at first, i am imagining how many interfaces I need to create now
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@kasozivincent107 You need to look at what you are doing with those UI elements. Why do you think you need them in the VM. Updating properties? Then just data bind to those properties instead.
@kasozivincent107
@kasozivincent107 4 жыл бұрын
No I am not using them for updating properties. For example i have custom listboxes that contain custom data templates and when an item is selected, I want to react depending on the value of the textblock wrapped inside my data template. Wait I will send you a pic on Twitter
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@kasozivincent107 Just bind to the SelectedItem property, that will be the data object that represents your data template. Then use the data object directly
@vivek.rathod
@vivek.rathod 3 жыл бұрын
Superb and very well explained Brian, thanks a ton!
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Thank you very much for watching
@Dinarqka
@Dinarqka 2 жыл бұрын
Hooooly, thats great! Thank you for video!
@BrianLagunas
@BrianLagunas 2 жыл бұрын
Thanks for watching
@resparzasoto
@resparzasoto 4 жыл бұрын
Really nice explication, thanks Brian, that approach with attached property, is so good!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you so much Rubén
@kasozivincent107
@kasozivincent107 4 жыл бұрын
🤭🤭🤭. I love the way you use these esoteric features in your code. First it was attributes(Prism Outlook dependency views) and now attached properties. I love this
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you so much.
@ЂорђеМилановић
@ЂорђеМилановић 4 жыл бұрын
Will there be any UWP/Uno Platform tutorials? 😁
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Yes, one day soon
@NickBullCSharp
@NickBullCSharp 4 жыл бұрын
"Don't include event args". Suddenly I get images of my past code from when I was learning MVVM flashing before me..... *gulp* 😜 This solution is really great, I love it. Thanks for sharing Brian
@BrianLagunas
@BrianLagunas 4 жыл бұрын
We've all done it at some point. Thanks for watching.
@rolandwatz7797
@rolandwatz7797 2 жыл бұрын
Where is this Delegate Command come from? I can't ype this code without getting errors
@BrianLagunas
@BrianLagunas 2 жыл бұрын
From the Prism.Core nuget package
@rolandwatz7797
@rolandwatz7797 2 жыл бұрын
@@BrianLagunas i installed it, but as soon I want to let the ViewModel inherit the Interface, it comes up with the Error, there is no interface. When I let it fix, it puts an "public Action Close{get => thro....; set =>.....) and the code, shown in your video is not the same any more and I got stuck.
@BrianLagunas
@BrianLagunas 2 жыл бұрын
@@rolandwatz7797 sorry, I don’t understand your problem
@rolandwatz7797
@rolandwatz7797 2 жыл бұрын
@@BrianLagunas No worries. It was a pebcak (Problem existing between chair and keyboard) . I had just to remove some and everything was fine
@davidwhite2011
@davidwhite2011 4 жыл бұрын
Are these projects available somewhere like your github or else where?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Unfortunately not yet, but this is the 2nd time someone mention that, so I should probably think of doing that. I just need to think of the best way to structure the repo. Each sample in it's own repo, are one repo for all KZbin videos and put all samples in that one repo.
@amilcarsantos6693
@amilcarsantos6693 4 жыл бұрын
All that code to close a window?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@amilcarsantos6693 If you care about maintainable, extensible, shareable, testable code, then yes. Add an interface and a single attached property that can be used anywhere. Have a better way? Would love to learn about it.
@amilcarsantos6693
@amilcarsantos6693 4 жыл бұрын
@@BrianLagunas I raise a CloseEventRequest on the VM and handle that event on the code behind. Sorry for my bad English.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@amilcarsantos6693 So you are doing something similar, just without the abstraction. That works too.
@meJevin
@meJevin 4 жыл бұрын
Hay I’ve been working with WPF for a while and at the place I work we don’t have a large team or a sufficiently large project to use MVVM. I wanted to ask you; based on you experience, what does MVVM really bring to the table in the context of small teams and fairly manageable projects? Aside from the over engineered code, insane amounts of unnecessary interfaces, abstractions and other weird stuff that blows up the code base by orders of magnitude. I’ve done some projects using this pattern via Prism, Caliburn.Micro and other MVVM libraries and so far I saw no advantages over a more free coding style and generally more simple architectural choices. Does this style of coding (MVVM) really only suit large projects with teams where there are tens of developers working and unit, integration and functional testing is required
@BrianLagunas
@BrianLagunas 4 жыл бұрын
As you know, writing software is extremely opinionated. I say, use what you can be successful with. If unit testing isn't something you do, and you don't have issues with maintenance, extensibility, and quality then just ignore all the design patterns and write a code-behind app. I would personally never write a code behind app. No matter how small the app is, I always use design patterns such as MVVM. If you are seeing over engineered code, insane amounts of interfaces, and weird stuff that blows up your code base by magnitudes, then I would argue you're doing something wrong. For one, the MVVM pattern only adds one additional file for each view. Other than that, nothing else will be much different. You'll still have your services, business objects, data access, and other utilities even in a code-behind project. However, I will say, you'll have many more problems to solve in a code-behind project that if you were to use a framework like Prism (and use it properly). Things such as communicating between views, navigation, controlling view/navigation lifetimes, handling parameters and object life cycles, just to name a few. I can write a WPF app that uses design patterns much faster than most can with code-behind. Use the tools you are comfortable with and can be successful with. Be pragmatic. In the end, the customer doesn't care how something was built, just as long as it works.
@jefrypozo4231
@jefrypozo4231 4 жыл бұрын
Very good. Thanks for taking your time to make these videos. I've worked with WPF applications before as part of some side projects and the way I did it was by having the reference to the viewModel on the view instead of the interface but using actions for the events as well. The way you did it reminds me of the EventListener or Sub/Pub pattern. But I really liked the part of the AttachedProperty. I'd like for you to make another talking about VisualState or Behaviors.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
That is a very similar approach. However, doing it that way still leaves a tight coupling between the View and a specific ViewModel type in the code behind. Hey, whatever works though. Customers don't care how it's written, they just want the app 😁
@LittleBobbyHasTables
@LittleBobbyHasTables 4 жыл бұрын
@@BrianLagunas A view should be tightly coupled to its own view model. Ex. CustomerView should be coupled to CustomerViewModel. Only a dependency from CustomerViewModel to CustomerView is wrong and should be avoided. The view uses the view model (bindings, even subscribing to view model events from code behind), not the other way around.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Coupling in any direction should be avoided. This increases testability and code reuse. This is exactly why you use binding. This decouples the source of data from the consumer of data. The view only know it is expecting something, it doesn't know where it is coming from. This becomes more important in production applications when using more advance patterns such as IoC. While you need to be pragmatic, loose coupling should always be the primary goal, although its not always possible. But you are right, in general there is always one view to one viewmodel.
@MuhammadSaleem-qz7xp
@MuhammadSaleem-qz7xp 3 жыл бұрын
Good job Brian. Keep it up! It has been a while since you posted a video. Busy?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Thank you. Yes, I have been very busy. Work, life, vacations. I'll be recording again soon. Maybe I should do an update video for everyone
@MuhammadSaleem-qz7xp
@MuhammadSaleem-qz7xp 3 жыл бұрын
It would be great. What about a Pluralsight course on Prism for Intermediate to Advanced users?
@BrianLagunas
@BrianLagunas 3 жыл бұрын
I already have some. They are part of the Prism Problems and Solutions series
@sergiotardo
@sergiotardo 4 жыл бұрын
Great, this way of closing Windows opens a lot of doors :), Talking about interfaces can you explain how to implement MaterialDesign on xamarin.forms? for Android an Ios? or how to do themming (dark ligth) in a rigth way for xamaring forms, thanks a lot for your videos they are the best, just all we need clear, shorts and hands on code. thanks!!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you for watching.
@nandkishorsonwale
@nandkishorsonwale 4 жыл бұрын
Really awesome video. Thanks Sir.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Glad you liked it
@dr.danielbuschert927
@dr.danielbuschert927 3 жыл бұрын
thx, helps me to close a form automatically after 1 minute
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Thanks for watching
@valeryngwa
@valeryngwa 4 жыл бұрын
So awesome. Thanks very much sir. This series of question-answer is going to be a must watch for me. I have a question sir. i can get row(s) selected in listview and datagridview, and combobox items, from my ViewModel. how can I select a row(s) or a(n) item(s) in my viewmodel? Thanks in advance.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thanks for watching! I'll see what I can do about your questions
@excitingfruit
@excitingfruit 4 жыл бұрын
Could you not just define an event in the viewmodel and have the Window subscribe to that event and close itself when the event gets invoked?
@BrianLagunas
@BrianLagunas 4 жыл бұрын
That is exactly what we are doing here. Instead of an event, we are using an Action as we are not passing the sender with the invocation.
@robertthurman8412
@robertthurman8412 Жыл бұрын
WOW!!!! this is amazing.
@BrianLagunas
@BrianLagunas Жыл бұрын
Thank you so much. You’re too kind
@predoirares6877
@predoirares6877 3 жыл бұрын
i tried to follow your steps and write my button just like you did and it still doesnt work
@BrianLagunas
@BrianLagunas 3 жыл бұрын
Can you determine what part exactly is not working? Set some break points and see where it is failing.
@BashaBill5
@BashaBill5 4 жыл бұрын
Hi Brian, great video. Maybe your next video could be about security (user accounts, permissions etc) in WPF. Its certainly something I would like to see a video on. 👍 Whether you would use ASP.NET Identity as a service, Identity Server or would you roll your own? And how you could hook those permissions into your controls (Infragistics, DevExpress or the WPF default) with Dependency Properties maybe, to enable/disable, hide or show controls etc. Maybe this is a course in itself. Or, is there an easy answer? 🤔
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Yeah, that would be more like a full blown course 😁.
@prabhakaranvelliangiri9655
@prabhakaranvelliangiri9655 4 жыл бұрын
Thank you Mr.Brain, Nice video more useful Soon I'll post my question 😊
@BrianLagunas
@BrianLagunas 4 жыл бұрын
I can't wait
@prabhakaranvelliangiri9655
@prabhakaranvelliangiri9655 4 жыл бұрын
@@BrianLagunas 1. How to make an some common data access class which will perform data opration. 2. Can we able to avoid implementation for the abstract method?
@julianturner6203
@julianturner6203 4 жыл бұрын
Thanks for the nice video, as always. 😃
@BrianLagunas
@BrianLagunas 4 жыл бұрын
My pleasure!
@solvedplus858
@solvedplus858 4 жыл бұрын
very awesome tutorial
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thanks for watching
@kunjalshah5123
@kunjalshah5123 4 жыл бұрын
Great video! Sound is synced to the video also!
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you for letting me know. I'll keep using this mic from now on.
@longuinni
@longuinni 4 жыл бұрын
Nice. The audio is perfect here.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Great to hear. I will stick to this mic for a few videos and see if anyone sees a sync issue.
@tusharparab9866
@tusharparab9866 4 жыл бұрын
First comment. Really solid code...
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Woot woot. Winner!!! Thanks for being the first!
@MrTellus
@MrTellus 4 жыл бұрын
This doesn't make people at work get on board with mvvm, it should be much simpler to implement. The interface isn't needed for the first part, which you maybe should have pointed out to make it more clear, it's only needed so not to hard code the vm name(s) in OnEnableW..and instead use the interface name to cover all that inherits the interface. I made it work in Xamarin (with prism) but what's recommended to use instead of Window.Loaded? (I solved it with view.SizeChanged but that seems bad).
@BrianLagunas
@BrianLagunas 4 жыл бұрын
This isn't about making people want to get on board with MVVM. It's for those already using MVVM. The interface is needed for the level of abstraction you should have. If you aren't using an interface your tightly coupled to the VM type. Meaning you can't reuse that code in a behavior or attached property on other views and VMs. It will be tightly coupled to a specific view and VM. This is as simple as it gets while staying loosely coupled and testable. You might want to use OnBindingContextChanged in XF. Not SizeChanged.
@MrTellus
@MrTellus 4 жыл бұрын
@@BrianLagunas I tried OnBind... before but somehow it got the tabbed page vm instead of the specific page vm, so it didn"t work.
@MrTellus
@MrTellus 4 жыл бұрын
BindingContextChanged without On worked :-) If one put public Action Close { get; set; } in a base vm, one can skip the need to add public Action Close { get; set; } to all vm's and also no interface is needed anymore. With a Style with setter for the attached property (at least in Xamarin) there's no need to set the property to true in all views/windows you just have to set it in one place. With my two tips I even persuaded some of my co-workers to use attached property :-)
@BrianLagunas
@BrianLagunas 4 жыл бұрын
@@MrTellus A base class can be useful IF every single VM in your app needs to close a window. Which chances are, that's not the case. Now you are exposing an API that will not be used to the consumers of that base class. Also, KEEP the interface. This provides more flexibility especially for those cases where you have a VM that does not derive a specific base class, and still need to close windows. This allows you to have the VM opt-in to closing VMs. My point is, always use the interface abstraction.
@MrTellus
@MrTellus 4 жыл бұрын
@@BrianLagunas I agree, but in Xamarin/Prism many always have a base class so I just wanted to mention the option. One of my co-workers was wondering about unsubscribing to the event handlers and where to do that, we guess it's where they are subscribed, which is OnEnableWindowClosingChanged, and for the view it's probably done in Disappearing but what to use for the vm? And since it's anonymous methods will it work even if one repeat the same code after += for -= (my co-worker said that it doesn't always work and setting it to null isn't an option)
@PhilippePastene
@PhilippePastene Жыл бұрын
Thanks!
@BrianLagunas
@BrianLagunas Жыл бұрын
You’re welcome
@essamsalah829
@essamsalah829 4 жыл бұрын
hi @Brian Lagunas i wanna tell you smth you are Awesome
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you so much for the kind words.
@ericbrooksby
@ericbrooksby 4 жыл бұрын
Thank you. Very Nice.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you for watching
@mahdihosseini5325
@mahdihosseini5325 4 жыл бұрын
thank you its awesome
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Thank you Mahdi!
@yevheniytymchishin8401
@yevheniytymchishin8401 4 жыл бұрын
The question is: what is the difference in the usages below: public interface IWindowClosable { Action Close { get; set; } } and public interface IWindowClosable { event Action Close; }
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Those are definitely different with some nuanced behavior differences. In this specific case, in a production app, an event might have been best as it will protect the delegate value (the Action) from being overwritten or possibly invoked outside the ViewModel.
@yevheniytymchishin8401
@yevheniytymchishin8401 4 жыл бұрын
@@BrianLagunas so, I choose the event ))
@yevheniytymchishin8401
@yevheniytymchishin8401 4 жыл бұрын
Thank you very much!)))
@BrianLagunas
@BrianLagunas 4 жыл бұрын
No problem. It was a great question. I just hope I said your name correctly 😁
@yevheniytymchishin8401
@yevheniytymchishin8401 4 жыл бұрын
@@BrianLagunas Yeah, for the person who pronouns my name first time - it is perfect )) Meanwhile I have almost the same question as in this video, who knows, may you will want to make another video. So: how to use PasswordBox properly with MVVM pattern?
@kasozivincent107
@kasozivincent107 4 жыл бұрын
Event arts are really pain in the ass. What a weird name. I love MVVM for helping me forget about them 🤣🤣🤣. Wait Brian, you just scared me😳😳😳. So you mean it’s bad practice to write delegate commands that take in WPF controls in the view model??
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Yes, very bad. Don't ever do that. VMs should never reference, define, or use UI controls
@denispleshakov9437
@denispleshakov9437 4 жыл бұрын
Nope. I prefer service locator concept... Interface with void close method, implemented on view and imported into view model.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
A static Service locator? No way! Not allowed in my app code base unless absolutely necessary. At least you have an abstraction from the view which is great. Just adding an addition mock on your test, but no biggie.
@turn1210
@turn1210 4 жыл бұрын
Brian Lagunas I hear complaints about servicelocators all the time, personally I use the .net core DI container and pass config settings in, Why don’t you recommend service locators¿
@BrianLagunas
@BrianLagunas 4 жыл бұрын
There are so many issues with using ServiceLocator. Just do a quick search for ServiceLocator anti-pattern and why its bad 😁
@denispleshakov9437
@denispleshakov9437 4 жыл бұрын
@@BrianLagunas no, not static service locator, just regular instance service locator. Just like said above, DI service locator. I'm using MEF to composr it. Also you can make it "layerd" and hierarchical to achieve different behavior on various layers of view model, isolate them and so on. Also our company has own service locator with its configurstor, reading it from xml, and it's fully instant, not static.
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Perfect! Glad to hear. Yes, that is good too. The abstraction is key. Implementation can be done in many ways.
@DenisElpashev
@DenisElpashev 4 жыл бұрын
I understand you made up the example just to demonstrate the concept, but... in a real world you must NEVER ever do it exactly as in this example, this would only make sense when you need to close window on some event coming from business logic or view model. But if you have "Close" btn in your window, then the only possible implementation in the event handler should be { this.Close(); } If you do in production something similar to what was shown in the video - I would fire you immediately, because IMHO over-engineering is much much worse than breaking any of programming concepts like mvvm or others..
@BrianLagunas
@BrianLagunas 4 жыл бұрын
Agreed! This should only be used when the requirement is to close a Window from a ViewModel. Be pragmatic. As I mentioned on the video, in production applications you'll need to think about how you should close a window.
@Trust_Me_Im_An_Engineer
@Trust_Me_Im_An_Engineer 4 жыл бұрын
SystemCommands.CloseWindow(this);
@BrianLagunas
@BrianLagunas 4 жыл бұрын
That doesn't do you any good in a VM. If you have access to "this" which is the window object, no need to call a command to close the window.
Copy all Files in Directories and Subdirectories in C#
7:22
Brian Lagunas
Рет қаралды 12 М.
It works #beatbox #tiktok
00:34
BeatboxJCOP
Рет қаралды 41 МЛН
Мен атып көрмегенмін ! | Qalam | 5 серия
25:41
C# Events События
14:36
codaza
Рет қаралды 55 М.
Clean Code is SLOW But REQUIRED? | Prime Reacts
28:22
ThePrimeTime
Рет қаралды 338 М.
Делегаты и события на практике
9:20
ExtremeCode
Рет қаралды 154 М.
C# Yield Return: What is it and how does it work?
15:09
Brian Lagunas
Рет қаралды 58 М.
View Models - WPF MVVM TUTORIAL #3
18:32
SingletonSean
Рет қаралды 90 М.
WPF in C# with MVVM using Caliburn Micro
1:23:30
IAmTimCorey
Рет қаралды 368 М.
Ranking Java Features Added from Versions 8 to 21!
27:03
Tales from the jar side
Рет қаралды 16 М.
Every Minute One Person Is Eliminated
34:46
MrBeast
Рет қаралды 47 МЛН
Which do I use, ConfigureAwait True or False?
6:53
Brian Lagunas
Рет қаралды 39 М.
It works #beatbox #tiktok
00:34
BeatboxJCOP
Рет қаралды 41 МЛН