Development Tip

WPF 프로그래밍 방법론

yourdevel 2020. 11. 23. 20:18
반응형

WPF 프로그래밍 방법론


3 개월 동안 WPF에서 앱을 프로그래밍 한 후 앱을 프로그래밍하는 방식에 대해 다시 생각했습니다 (너무 늦었을 수도 있습니다). 내 앱에서 내 도구가 관리하는 소프트웨어의 API를 사용하고 있습니다. 16 개의 클래스를 포함하는 DAL이 있는데 그 중 3 개는 싱글 톤입니다. 나는 .cs파일에 논리가 있고 XAML코스를 벗어났습니다. 내 질문은 WPF로 작성된 앱이 MVVM을 사용해야한다는 많은 의견이 있으며, 그러면 코드를 더 유용하고 읽기 쉽게 만들 수 있다는 것입니다. 코드를 MVVM으로 변환 할 수 있습니까? MVVM의 실제 의미는 무엇입니까 (Wikipedia 또는 수동 정의가 아님)?

또한 SQL 쿼리를 사용하고 EF (Entity Framework)에 대한 문서를 읽었습니다. MVVM과 EF가 같은 프로젝트에서 함께 공존 할 수 있습니까?

내 질문은 약간의 초보자 질문 (나는 초보자입니다 : P)이고 추상적 인 질문이라는 것을 알고 있지만 제가 작성할 앱이 지금 쓸 수있는 최고가 될 것임을 알고 싶습니다. :)


MVVM의 실제 의미는 UI가 데이터가 아닙니다. 데이터는 데이터이고 UI는 UI 입니다.

즉, 프로그램 로직 (종종 비즈니스 로직이라고 함)이 UI 구성 요소의 상태에 밀접하게 결합되거나 종속되는 방식으로 애플리케이션을 개발해서는 안되며, 대신 데이터 항목의 상태 (모델)에 종속되도록해야합니다. , 또는보기 모델).

예를 들어 다른 프레임 워크 (예 : winforms)에서 텍스트 상자와 단추가 포함 된 화면이있는 경우 일반적으로 단추에 클릭 이벤트 처리기를 추가 한 다음 텍스트 상자에서 텍스트를 읽습니다. MVVM에서 TextBox의 Text 속성은 ViewModel의 문자열 속성에 바인딩되어야하고 버튼은 ViewModel의 Command에도 바인딩되어야합니다.

이를 통해 UI (ViewModel)를 추상화 할 수 있으므로 앞서 말했듯이 애플리케이션 로직이 UI가 아니라 추상화에 의존 할 수 있습니다.

이것은 UI와 로직에서 엄청난 양의 확장 성을 허용하고 UI 동작의 많은 부분이 ViewModel에 정의되어 있기 때문에 UI 동작의 여러 측면에 대한 테스트 가능성을 허용합니다.

MVVM의 다른 측면도 있지만 주요 실현은 그 점입니다.

편집하다:

답변의 완전성을 위해 이에 대한 구체적인 예를 추가하겠습니다.

1-비 MVVM WPF :

XAML :

<StackPanel>
   <TextBox x:Name="txtLastName"/>
   <Button Content="Click Me" Click="Button_Click"/>
</StackPanel>

뒤에있는 코드 :

private void Button_Click(object sender, EventArgs e)
{
    //Assuming this is the code behind the window that contains the above XAML.
    var lastname = this.txtLastName.Text; 

    //Here you do some actions with the data obtained from the textbox
}

2-MVVM WPF :

XAML :

<StackPanel>
   <StackPanel.DataContext>
       <my:MyViewModel/>
   </StackPanel.DataContext>
   <TextBox Text="{Binding LastName}"/>
   <Button Content="Click Me" Command="{Binding MyCommand}"/>
</StackPanel>

ViewModel :

public class MyViewModel
{
    public string LastName { get; set; }

    public Command MyCommand { get; set; }

    public MyViewModel()
    {
        // The command receives an action on the constructor,
        // which is the action to execute when the command is invoked.
        MyCommand = new Command(ExecuteMyCommand); 
    }

    private void ExecuteMyCommand()
    {
        //Only for illustration purposes, not really needed.
        var lastname = this.LastName; 

        //Here you do some actions with the data obtained from the textbox
    }
}

위의 예에서 볼 수 있듯이 ViewModel에는 View에 대한 참조가 전혀 포함되어 있지 않습니다. 따라서 뷰는 {Bindings}제자리에 유지되는 한 무엇이든 될 수 있습니다 .

마술처럼 함께 작동하도록 만드는 접착제는 DataContext모든 바인딩이 해결되는 개체 인 WPF UI 요소 속성입니다.

양방향 바인딩을 활성화하는 ViewModel의 속성 변경 알림과 같은 다른 것들이 있지만이 답변의 범위를 벗어납니다.

Also keep in mind that MVVM is a design pattern, whereas WPF is a framework. MVVM is also being currently applied in other technologies (there is currently a lot of buzz about MVVM for the web, with JavaScript and stuff like that)

I suggest you read the books mentioned in other answers as well as this Tutorial for more WPF-specific aspects.


My question is, I see a lot of comments that an app written in WPF should use MVVM, and this will make the code more usable and readable, can I transform my code to be MVVM?

There's no requirement that you need to use the MVVM pattern - none. You need to consider the complexity of the app you are building and the development groups skill-set. Generally speaking, if it's a small or small/medium app then MVVM may be over-engineering. If the group's skills/talent aren't a good fit for a separated presentation pattern, then MVVM may not be a good decision.

If done right, then MVVM gives you all the sorts of benefits that you've read about. Conversely, if it's done wrong, then it can be a development and maintanence nightmare - definitely not more readable and usable. From personal experience, I think it's easier to work on a poorly written code-behind app rather than a poorly written MVVM based one.

Sure, you can rewrite your current app to the MVVM pattern. Just remove your code-behind and put it into your view-models, helper classes, repository classes, biz-logic classes, etc. Don't fall into the trap of putting everything into you view-models, creating an MVVM-glorified code-behind.

I also use SQL queries and I read a paper about EF (Entity Framework), can MVVM and EF leave together in the same project?

Sure, they can. Just remember that EF is a data access technology and MVVM is a design pattern. You'll probably use EF in your DAL classes that you mention.

One final thought, if you decide to go down the MVVM route then you should consider using a framework that facilitates it, like Prism. Oh, and be prepared for quite a bit of learning and frustration.


I would definitely look into DependencyInjection, using a framework like Unity.

Your Singleton classes could be registered with a DependencyInjection container and injected into constructors of other classes (such as ViewModels). So could other DAL classes which need to be instantiated regularly and injected into classes.

DependencyInjection is the single most important design pattern when developing large enterprise software applications and is applicable for both Client & Server code. MVVM is a nice pattern but won't address the issue of overall application complexity related to dependency coupling.


These are mine specific to MVVM

1) Increases the "Blendability" of your views (ability to use Expression Blend to design views). This enables a separation of responsibilities on teams that are lucky enough to have a designer and a programmer... each can work independent of the other.

2) "Lookless" view logic. Views are agnostic from the code that runs behind them, enabling the same view logic to be reused across multiple views or have a view easily retooled or replaced. Seperates concerns between "behavior" and "style".

3) No duplicated code to update views. In code-behind you will see a lot of calls to "myLabel.Text = newValue" sprinkled everywhere. With MVVM you can be assured the view is updated appropriately just by setting the underlying property and all view side-effects thereof.

4) Testability. Since your logic is completely agnostic of your view (no "myLabel.Text" references), unit testing is made easy. You can test the behavior of a ViewModel without involving its view. This also enabled test-driven development of view behavior, which is almost impossible using code-behind.

The other two patterns are really sort of separate in terms of the concerns they address. You can use MVVM with MVP and MVC (most good samples out there do some form of this).

In fact, MVP (w/ a Passive View, rather than a Supervising Controller) is really just a variant of MVVM, in my opinion.

참고URL : https://stackoverflow.com/questions/14381402/wpf-programming-methodology

반응형