How to Close Windows from a ViewModel in C#

Sdílet
Vložit
  • čas přidán 7. 09. 2024
  • In this video, I answer the popular MVVM question, "How to Close Windows from a ViewModel". When you're developing WPF applications using the MVVM design pattern, the number one rule is "no UI elements in the ViewModel". Well, if I am not allowed to have UI elements in the ViewModel, how on earth do I close windows from a ViewModel? Easy! With a simple layer of adbstraction.
    I will teach you how to leverage the power of interfaces to abstract away the Window object from the ViewModel and still have the ability to close Windows from your ViewModel.
    Not only that, but we will see how we can even prevent the Window from closing, even when clicking on the Window's close button (the X in the top riht corner of the Window), using business logic in our ViewModel by leveraging the flexibility of our abstraction.
    I'll even show you how to reduce code duplication by consolidating our abstraction login into an AttachedProperty which can be used on any Window in our application. Write once, use everywhere!
    Be sure to watch my new Pluralsight course "Introduction to Prism for WPF":
    pluralsight.px...
    Sponsor Me:
    github.com/spo...
    Follow Me:
    Twitter: / brianlagunas
    Twitch: / brianlagunas
    Blog: brianlagunas.com
    GitHub: github.com/bri...

Komentáře • 200

  • @freemax32
    @freemax32 Před 3 lety +3

    That feeling when there is a specific task and you have found a solution!

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      Woot woot! I'm glad this video was helpful

  • @faisletoismeme
    @faisletoismeme Před 2 lety +3

    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.

  • @MudasarRauf
    @MudasarRauf Před 4 lety +5

    thank you @Brian Finally i understand how and when to use attached properties along with the the window closing :-)

  • @rosscarlson3701
    @rosscarlson3701 Před rokem +1

    This is cleaner, less-coupled method than what I've been using ... I'm going to switch to this. Thanks!

  • @mrt7948
    @mrt7948 Před 2 lety +1

    that you very much, these kind of tips are really helpful for beginners like me.

  • @harvey6456
    @harvey6456 Před rokem

    I combine this demo with DialogService, thanks a lot.

  • @pickedupapencil
    @pickedupapencil Před 4 lety +1

    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  Před 4 lety

      You definitely did it the right way my friend.

  • @Dinarqka
    @Dinarqka Před 2 lety +1

    Hooooly, thats great! Thank you for video!

  • @VinuP2023
    @VinuP2023 Před 4 lety +1

    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

  • @kasozivincent107
    @kasozivincent107 Před 4 lety

    🤭🤭🤭. 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

  • @DirkStoermer
    @DirkStoermer Před rokem +1

    Cool, nice approach. That's exactly what I was looking for. Many thanks.

  • @robertthurman8412
    @robertthurman8412 Před rokem +1

    WOW!!!! this is amazing.

  • @habanerohoncho
    @habanerohoncho Před 4 lety +1

    Thank you sir. Your stuff is golden. Audio-video sync looking/sounding good to me.

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +1

      So good to hear. I guess i will use this mic from now on. Thanks for letting me know.

  • @NickBullCSharp
    @NickBullCSharp Před 4 lety

    "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  Před 4 lety +1

      We've all done it at some point. Thanks for watching.

  • @hussainhussaini2267
    @hussainhussaini2267 Před 3 lety +1

    Very helpful. Can you please also make a video on how to open a new window from the viewmodel?

  • @noaml-1
    @noaml-1 Před 4 lety +2

    Hi Brian, it would be great if you add this feature to Prism.

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      This feature already exists in Prism when you use the IDialogService 😀

  • @smellybathroom
    @smellybathroom Před rokem +1

    omgosh - thank you very much for this!

    • @BrianLagunas
      @BrianLagunas  Před rokem

      You’re very welcome. Thanks for watching

  • @Zonawanialonnua
    @Zonawanialonnua Před 4 lety +1

    Hi Brian!
    You are a wonderful teacher!
    Thank!

  • @dr.danielbuschert927
    @dr.danielbuschert927 Před 3 lety +1

    thx, helps me to close a form automatically after 1 minute

  • @resparzasoto
    @resparzasoto Před 4 lety +1

    Really nice explication, thanks Brian, that approach with attached property, is so good!

  • @MuhammadSaleem-qz7xp
    @MuhammadSaleem-qz7xp Před 3 lety +1

    Good job Brian. Keep it up! It has been a while since you posted a video. Busy?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      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 Před 3 lety

      It would be great. What about a Pluralsight course on Prism for Intermediate to Advanced users?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      I already have some. They are part of the Prism Problems and Solutions series

  • @vivek.rathod
    @vivek.rathod Před 3 lety +1

    Superb and very well explained Brian, thanks a ton!

  • @jefrypozo4231
    @jefrypozo4231 Před 4 lety +1

    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  Před 4 lety

      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 Před 4 lety

      @@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  Před 4 lety

      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.

  • @nandkishorsonwale
    @nandkishorsonwale Před 4 lety +1

    Really awesome video. Thanks Sir.

  • @barti890300
    @barti890300 Před 2 lety

    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?

  • @user-ho6se8ow3b
    @user-ho6se8ow3b Před rokem +1

    Thanks!

  • @sergiotardo
    @sergiotardo Před 4 lety +2

    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!!

  • @kunjalshah5123
    @kunjalshah5123 Před 4 lety +1

    Great video! Sound is synced to the video also!

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      Thank you for letting me know. I'll keep using this mic from now on.

  • @douglasbates389
    @douglasbates389 Před 3 lety

    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  Před 3 lety

      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 Před 3 lety

      @@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.

  • @cpmoliveira
    @cpmoliveira Před 4 lety +1

    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  Před 4 lety +1

      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 Před 4 lety

      @@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  Před 4 lety

      @@cpmoliveira Your approach will depend on your app architecture. I'm not just talking about MVVM. I mean your overall app architecture.

    • @cpmoliveira
      @cpmoliveira Před 4 lety

      @@BrianLagunas In time, I'm working on a WPF project with .NET 5 and Prism 8.

  • @solvedplus858
    @solvedplus858 Před 3 lety +1

    very awesome tutorial

  • @julianturner6203
    @julianturner6203 Před 4 lety +1

    Thanks for the nice video, as always. 😃

  • @prabhakaranvelliangiri9655

    Thank you Mr.Brain,
    Nice video more useful
    Soon I'll post my question 😊

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +1

      I can't wait

    • @prabhakaranvelliangiri9655
      @prabhakaranvelliangiri9655 Před 4 lety

      @@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?

  • @longuinni
    @longuinni Před 4 lety

    Nice. The audio is perfect here.

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      Great to hear. I will stick to this mic for a few videos and see if anyone sees a sync issue.

  • @TheCodeVicious
    @TheCodeVicious Před 3 lety +1

    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  Před 3 lety

      You can always get the parent window of a user control if you need it

  • @essamsalah829
    @essamsalah829 Před 4 lety +1

    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  Před 4 lety +1

      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.

  • @BashaBill5
    @BashaBill5 Před 4 lety

    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  Před 4 lety +1

      Yeah, that would be more like a full blown course 😁.

  • @mehransarrafi7790
    @mehransarrafi7790 Před 2 lety

    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  Před 2 lety +1

      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

  • @essamsalah829
    @essamsalah829 Před 4 lety +2

    hi @Brian Lagunas
    i wanna tell you smth
    you are Awesome

  • @manuelballesteros79
    @manuelballesteros79 Před 2 lety

    @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  Před 2 lety +1

      The attached property is defined in a new class called WindowCloser and NOT in the VM.

  • @tweshlyallpuri
    @tweshlyallpuri Před 4 lety

    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  Před 4 lety

      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 Před 4 lety

      @@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 :))

  • @mahdihosseini5325
    @mahdihosseini5325 Před 4 lety +1

    thank you its awesome

  • @ericbrooksby
    @ericbrooksby Před 4 lety

    Thank you. Very Nice.

  • @valeryngwa
    @valeryngwa Před 4 lety

    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  Před 4 lety +1

      Thanks for watching! I'll see what I can do about your questions

  • @asdswx
    @asdswx Před 11 měsíci

    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

  • @tomroberts1216
    @tomroberts1216 Před 3 lety

    Thanks Brian. Very useful. Q: Would this change at all if you were to use the autoviewmodellocator? If so, what would change?

    • @tomroberts1216
      @tomroberts1216 Před 3 lety

      Just to put my question in context. You used Datacontext and autoviewmodellocator eliminates the need for the use of Datacontext.

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      @@tomroberts1216 Nothing would change if you used AutowireViewModel. It works the same

  • @user-jo1mz4se4j
    @user-jo1mz4se4j Před 4 lety +1

    Will there be any UWP/Uno Platform tutorials? 😁

  • @PinkyParu
    @PinkyParu Před 4 lety

    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  Před 4 lety

      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 😁

  • @taab84
    @taab84 Před 3 lety

    This approach will work if instean we try to print Ui content element (like datagrid)?

  • @bjorn1409
    @bjorn1409 Před 3 lety

    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  Před 3 lety

      You might want to hook into the DataContextChanged event and then hook into any events on the VM. Let me know if that works

  • @yevheniytymchishin8401

    Thank you very much!)))

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      No problem. It was a great question. I just hope I said your name correctly 😁

    • @yevheniytymchishin8401
      @yevheniytymchishin8401 Před 4 lety +1

      @@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?

  • @zeljkolazic2542
    @zeljkolazic2542 Před 3 lety

    if (DataContext is ICloseWindow vm)...error: vm does not exist in the current context. Does this only work using Prism?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      You might be using an older version of C# where this syntax isn't supported. You'll just have to use a different syntax.

  • @mywildlifestories3793
    @mywildlifestories3793 Před 4 lety

    Hey Brian, how do we identify the performance issues in wpf app and what is best approach to resolve the same?

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      Start with the built in performance and profiling tools built into Visual Studio. Can also use other 3rd party tools you could use.

  • @osman3404
    @osman3404 Před 4 lety

    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  Před 4 lety

      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.

  • @taruntirkey
    @taruntirkey Před 4 lety

    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?

  • @tusharparab9866
    @tusharparab9866 Před 4 lety +1

    First comment. Really solid code...

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +1

      Woot woot. Winner!!! Thanks for being the first!

  • @AbsurdKangaroo
    @AbsurdKangaroo Před 3 lety

    Care to comment on how you would do it without Prism? Or is that not worth considering?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      This will work with or without Prism. It has no impact

    • @AbsurdKangaroo
      @AbsurdKangaroo Před 3 lety

      @@BrianLagunas thanks! you mentioned “delegatecommand from Prism” so that threw me off.

    • @BrianLagunas
      @BrianLagunas  Před 3 lety

      Ahh yes, if not using DelegateCommand you'll use your own ICommand implementation

  • @meJevin
    @meJevin Před 4 lety

    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  Před 4 lety +2

      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.

  • @harsheng
    @harsheng Před 4 lety

    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  Před 4 lety +1

      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.

  • @solvedplus858
    @solvedplus858 Před 2 lety

    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  Před 2 lety +1

      I plan on doing a video on creating a dialog service. Yes, using ImageSource breaks MVVM.

    • @solvedplus858
      @solvedplus858 Před 2 lety

      @@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  Před 2 lety +1

      Just use a string with the image path. If you absolutely have an image Source, use a converter

    • @solvedplus858
      @solvedplus858 Před 2 lety

      @@BrianLagunas I get the image from clipboard while paste, or take snip from the screen

  • @yevheniytymchishin8401

    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  Před 4 lety

      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 Před 4 lety +1

      @@BrianLagunas so, I choose the event ))

  • @sem4461
    @sem4461 Před 3 lety

    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  Před 3 lety

      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  Před 3 lety +1

      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 Před 3 lety +1

      @@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 :)

  • @predoirares6877
    @predoirares6877 Před 2 lety

    i tried to follow your steps and write my button just like you did and it still doesnt work

    • @BrianLagunas
      @BrianLagunas  Před 2 lety

      Can you determine what part exactly is not working? Set some break points and see where it is failing.

  • @AbsurdKangaroo
    @AbsurdKangaroo Před 3 lety

    I’m having trouble applying the attached property in xaml. I notice yours auto fills.

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      Hard to say without seeing the code. Make sure you have properly defined the attached property and build the project

    • @AbsurdKangaroo
      @AbsurdKangaroo Před 3 lety +1

      @@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  Před 3 lety

      Glad you figured it out. VS has been the root of a lot of my issues recently.

    • @wifixx
      @wifixx Před 3 lety

      Having the same issue here, can't see a single thing when I enter "local:" in xaml. Can't even link my view model.

  • @lukaszluczko
    @lukaszluczko Před 3 lety

    @Brian How to open new window difrent than main window?

    • @BrianLagunas
      @BrianLagunas  Před 3 lety +1

      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 Před 3 lety +1

      @@BrianLagunas will be greate if You prepare video about that.

  • @excitingfruit
    @excitingfruit Před 4 lety

    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  Před 4 lety

      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.

  • @rolandwatz7797
    @rolandwatz7797 Před rokem

    Where is this Delegate Command come from? I can't ype this code without getting errors

    • @BrianLagunas
      @BrianLagunas  Před rokem

      From the Prism.Core nuget package

    • @rolandwatz7797
      @rolandwatz7797 Před rokem

      @@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  Před rokem

      @@rolandwatz7797 sorry, I don’t understand your problem

    • @rolandwatz7797
      @rolandwatz7797 Před rokem +1

      @@BrianLagunas No worries. It was a pebcak (Problem existing between chair and keyboard) . I had just to remove some and everything was fine

  • @kasozivincent107
    @kasozivincent107 Před 4 lety

    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  Před 4 lety +1

      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 Před 4 lety

      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  Před 4 lety +1

      @@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 Před 4 lety

      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  Před 4 lety +1

      @@kasozivincent107 Just bind to the SelectedItem property, that will be the data object that represents your data template. Then use the data object directly

  • @davidwhite2011
    @davidwhite2011 Před 4 lety +1

    Are these projects available somewhere like your github or else where?

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +2

      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 CZcams videos and put all samples in that one repo.

    • @amilcarsantos6693
      @amilcarsantos6693 Před 4 lety

      All that code to close a window?

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +1

      @@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 Před 4 lety

      @@BrianLagunas I raise a CloseEventRequest on the VM and handle that event on the code behind. Sorry for my bad English.

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      @@amilcarsantos6693 So you are doing something similar, just without the abstraction. That works too.

  • @MrTellus
    @MrTellus Před 4 lety

    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  Před 4 lety

      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 Před 4 lety

      @@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 Před 4 lety +1

      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  Před 4 lety

      @@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 Před 4 lety

      @@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)

  • @kasozivincent107
    @kasozivincent107 Před 4 lety

    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  Před 4 lety +1

      Yes, very bad. Don't ever do that. VMs should never reference, define, or use UI controls

  • @denispleshakov9437
    @denispleshakov9437 Před 4 lety

    Nope. I prefer service locator concept... Interface with void close method, implemented on view and imported into view model.

    • @BrianLagunas
      @BrianLagunas  Před 4 lety

      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 Před 4 lety

      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  Před 4 lety

      There are so many issues with using ServiceLocator. Just do a quick search for ServiceLocator anti-pattern and why its bad 😁

    • @denispleshakov9437
      @denispleshakov9437 Před 4 lety +1

      @@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  Před 4 lety

      Perfect! Glad to hear. Yes, that is good too. The abstraction is key. Implementation can be done in many ways.

  • @Trust_Me_Im_An_Engineer

    SystemCommands.CloseWindow(this);

    • @BrianLagunas
      @BrianLagunas  Před 4 lety +1

      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.

  • @DenisElpashev
    @DenisElpashev Před 4 lety +1

    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  Před 4 lety +1

      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.