IT

MVVM 템플릿의 좋은 예

lottoking 2020. 6. 23. 07:01
반응형

MVVM 템플릿의 좋은 예


현재 Microsoft MVVM 템플릿으로 작업하고 있으며 자세한 예제가 부족하다는 것을 알았습니다. 포함 된 ContactBook 예제는 매우 적은 Command 처리를 보여 주며 내가 찾은 다른 예제는 개념은 비슷하지만 약간 다른 접근법을 사용하지만 여전히 복잡성이 부족한 MSDN Magazine 기사에서 얻은 것입니다. 최소한 기본 CRUD 작업과 대화 상자 / 콘텐츠 전환을 보여주는 괜찮은 MVVM 예가 있습니까?


모든 사람의 제안이 정말 유용했으며 좋은 자료 목록을 작성하기 시작합니다.

프레임 워크 / 템플릿

유용한 기사

스크린 캐스트

추가 라이브러리


불행히도 모든 것을 수행하는 훌륭한 MVVM 예제 앱은 없으며 작업을 수행하는 다양한 방법이 있습니다. 첫째, 의존성 주입, 명령, 이벤트 집계 등과 같은 편리한 도구를 제공하여 자신에게 적합한 다양한 패턴을 쉽게 시도 할 수 있기 때문에 앱 프레임 워크 중 하나에 익숙해지고 싶을 수도 있습니다 (Prism은 적절한 선택입니다). .

프리즘 릴리즈 :
http://www.codeplex.com/CompositeWPF

꽤 작은 예제 앱 (주식 거래자)과 많은 작은 예제 및 방법이 포함되어 있습니다. 최소한 사람들이 MVVM을 실제로 작동시키는 데 사용하는 몇 가지 일반적인 하위 패턴에 대한 좋은 데모입니다. 그들은 CRUD와 대화 모두에 대한 예를 가지고 있다고 생각합니다.

프리즘이 모든 프로젝트에 반드시 필요한 것은 아니지만 친숙해지는 것이 좋습니다.

CRUD : 이 부분은 매우 쉽습니다. WPF 양방향 바인딩을 사용하면 대부분의 데이터를 정말 쉽게 편집 할 수 있습니다. 실제 트릭은 UI를 쉽게 설정할 수있는 모델을 제공하는 것입니다. 최소한 ViewModel (또는 비즈니스 객체)이 INotifyPropertyChanged바인딩을 지원하도록 구현 하고 속성을 UI 컨트롤에 직접 바인딩 할 수 있지만 IDataErrorInfo유효성 검사 를 위해 구현할 수도 있습니다 . 일반적으로 일종의 ORM 솔루션을 사용하면 CRUD를 설정하는 것이 간단합니다.

이 기사는 간단한 crud 작업을 보여줍니다 : http://dotnetslackers.com/articles/wpf/WPFDataBindingWithLINQ.aspx

LinqToSql을 기반으로하지만 예제와 관련이 없습니다. 중요한 것은 비즈니스 오브젝트가 구현하는 것입니다 INotifyPropertyChanged(LinqToSql에 의해 생성 된 클래스가 수행함). MVVM은 그 예의 요점이 아니지만이 경우에는 중요하지 않다고 생각합니다.

이 기사는 데이터 유효성 검사를 보여줍니다
http://blogs.msdn.com/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx

또한 대부분의 ORM 솔루션은 이미 구현 한 클래스를 생성 IDataErrorInfo하며 일반적으로 사용자 지정 유효성 검사 규칙을 쉽게 추가 할 수있는 메커니즘을 제공합니다.

대부분의 경우 ORM이 생성 한 객체 (모델)를 가져 와서 저장 / 삭제 명령이있는 ViewModel에 래핑하여 UI를 모델 속성에 바로 바인딩 할 수 있습니다.

뷰는 다음과 같습니다 (ViewModel에는 ItemORM에서 작성된 클래스와 같이 모델을 보유 하는 특성이 있음).

<StackPanel>
   <StackPanel DataContext=Item>
      <TextBox Text="{Binding FirstName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
      <TextBox Text="{Binding LastName, Mode=TwoWay, ValidatesOnDataErrors=True}" />
   </StackPanel>
   <Button Command="{Binding SaveCommand}" />
   <Button Command="{Binding CancelCommand}" />
</StackPanel>

대화 상자 : 대화 상자와 MVVM은 약간 까다 롭습니다. 대화 상자와 함께 다양한 Mediator 접근 방식을 사용하는 것을 선호합니다.이 StackOverflow 질문에서 조금 더 자세히 읽을 수 있습니다
.WPF MVVM 대화 상자 예제

고전적인 MVVM이 아닌 일반적인 접근 방식은 다음과 같이 요약 할 수 있습니다.

커밋 및 취소 작업에 대한 명령을 표시하는 대화 상자 ViewModel의 기본 클래스, 대화 상자를 닫을 준비가되었음을 뷰에 알리는 이벤트 및 모든 대화 상자에 필요한 항목

A generic view for your dialog - this can be a window, or a custom "modal" overlay type control. At its heart it is a content presenter that we dump the viewmodel into, and it handles the wiring for closing the window - for example on data context change you can check if the new ViewModel is inherited from your base class, and if it is, subscribe to the relevant close event (the handler will assign the dialog result). If you provide alternative universal close functionality (the X button, for instance), you should make sure to run the relevant close command on the ViewModel as well.

Somewhere you need to provide data templates for your ViewModels, they can be very simple especially since you probably have a view for each dialog encapsulated in a separate control. The default data template for a ViewModel would then look something like this:

<DataTemplate DataType="{x:Type vmodels:AddressEditViewModel}">
   <views:AddressEditView DataContext="{Binding}" />
</DataTemplate>

The dialog view needs to have access to these, because otherwise it won't know how to show the ViewModel, aside from the shared dialog UI its contents are basically this:

<ContentControl Content="{Binding}" />

The implicit data template will map the view to the model, but who launches it?

This is the not-so-mvvm part. One way to do it is to use a global event. What I think is a better thing to do is to use an event aggregator type setup, provided through dependency injection - this way the event is global to a container, not the whole app. Prism uses the unity framework for container semantics and dependency injection, and overall I like Unity quite a bit.

Usually, it makes sense for the root window to subscribe to this event - it can open the dialog and set its data context to the ViewModel that gets passed in with a raised event.

Setting this up in this way lets ViewModels ask the application to open a dialog and respond to user actions there without knowing anything about the UI so for the most part the MVVM-ness remains complete.

There are times, however, where the UI has to raise the dialogs, which can make things a bit trickier. Consider for example, if the dialog position depends on the location of the button that opens it. In this case you need to have some UI specific info when you request a dialog open. I generally create a separate class that holds a ViewModel and some relevant UI info. Unfortunately some coupling seems unavoidable there.

Pseudo code of a button handler that raises a dialog which needs element position data:

ButtonClickHandler(sender, args){
    var vm = DataContext as ISomeDialogProvider; // check for null
    var ui_vm = new ViewModelContainer();
    // assign margin, width, or anything else that your custom dialog might require
    ...
    ui_vm.ViewModel = vm.SomeDialogViewModel; // or .GetSomeDialogViewModel()
    // raise the dialog show event
}

The dialog view will bind to position data, and pass the contained ViewModel to the inner ContentControl. The ViewModel itself still doesn't know anything about the UI.

In general I don't make use of the DialogResult return property of the ShowDialog() method or expect the thread to block until the dialog is closed. A non-standard modal dialog doesn't always work like that, and in a composite environment you often don't really want an event handler to block like that anyhow. I prefer to let the ViewModels deal with this - the creator of a ViewModel can subscribe to its relevant events, set commit/cancel methods, etc, so there is no need to rely on this UI mechanism.

So instead of this flow:

// in code behind
var result = somedialog.ShowDialog();
if (result == ...

I use:

// in view model
var vm = new SomeDialogViewModel(); // child view model
vm.CommitAction = delegate { this.DoSomething(vm); } // what happens on commit 
vm.CancelAction = delegate { this.DoNothing(vm); } // what happens on cancel/close (optional)
// raise dialog request event on the container

I prefer it this way because most of my dialogs are non-blocking pseudo-modal controls and doing it this way seems more straightforward than working around it. Easy to unit test as well.


Jason Dolinger made a good screencast of MVVM. Like Egor mentioned there is no one good example. They are all over. Most are good MVVM examples, but not when you get into complex issues. Everyone has their own way. Laurent Bugnion has a good way to communicate between viewmodels as well. http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx Cinch is also a good example. Paul Stovel has a good post that explains a lot too with his Magellan framework.


Have you looked at Caliburn? The ContactManager sample has a lot of good stuff in it. The generic WPF samples also provide a good overview of commands. The documentation is fairly good and the forums are active. Recommended!


Found this one useful. Has code too.

http://msdn.microsoft.com/en-us/magazine/dd419663.aspx


The sample project in the Cinch framework shows basic CRUD and navigation tools. It's a fairly good example of using MVVM, and includes a multi-part article explaining its usage and motivations.


I also shared in your frustration. I'm writing an application and I had these 3 requirements:

  • Extensible
  • WPF with MVVM
  • GPL compatible examples

All I found were bits and pieces, so I just started writing it the best I could. After I got into it a bit, I realized there might be other people (like yourself) who could use a reference application, so I refactored the generic stuff out into a WPF/MVVM application framework and released it under the LGPL. I named it SoapBox Core. If you go to the downloads page, you'll see it comes with a small demo application, and the source code for that demo application is also available for download. Hope you find that helpful. Also, email me at scott {at} soapboxautomation.com if you want more info.

EDIT: Also posted a CodeProject article explaining how it works.


Here I am adding link of a WPF(Inventory Management App) application which using MVVM architecture designed by me .

Its UI is awesome. https://github.com/shivam01990/InventoryManagement


Even I shared the frustration until I took the matter into my hands. I started IncEditor.

IncEditor (http://inceditor.codeplex.com) is an editor that tries to introduce developers to WPF, MVVM & MEF. I started it and managed to get some functionality like 'theme' support. I am no expert in WPF or MVVM or MEF so I can't put a lot of functionality in it. I make a sincere request to you guys to make it better so that nutters like me can understand it better.


I have written a simple MVVM example from scratch on code project here is the link MVVM WPF step by step. It starts from a simple 3 layer architecture and graduates you to use some framework like PRISM.

enter image description here

참고URL : https://stackoverflow.com/questions/1662309/good-examples-of-mvvm-template

반응형