UWP 앱을 MVVM으로 만들 때 먼저 할 일
13094 단어 UWPVisualStudio2017Windows10MVVMC#
※Visual Studio 2017을 전제로 하고 있습니다.
Visual Studio에서 새 프로젝트 만들기
이미 만든 분은 날려주세요.
빈 프로젝트 만들기
메뉴에서 프로젝트를 새로 작성.

빈 앱(유니버설 Windows)을 선택하고 저장 위치를 선택합니다.

컴파일 할 대상 버전과 사용하는 API에 따라 최소 버전을 적절하게 선택하십시오.

작성 직후는 이러한 폴더 구조로 되어 있습니다.

프로젝트 작성 직후에 할 일
MVVM 및 현지화용 폴더 만들기
만들 폴더는 다음 5개
MVVM 및 현지화용 폴더 만들기
만들 폴더는 다음 5개
상단 3개는 MVVM용, 하단 2개는 현지화용입니다. 현지화 폴더는 언어에 따라 늘려갑니다.
자세한 것은 「 UI 문자열을 리소스에 저장 」를 참고로.

MainPage를 Views 폴더로 이동
프로젝트에 처음부터 포함된 MainPage를 Views 폴더로 이동합니다. 여기에서는 다음 작업을 합니다.
MainPage.xaml,MainPage.xaml.cs 파일 이동
MainPage.xaml을 드래그 앤 드롭으로 Views 폴더로 가져갑니다. 이제 코드 숨김인 MainPage.xaml.cs도 함께 Views 폴더에 들어갑니다.

MainPage 클래스의 네임스페이스 수정
MainPage 클래스는 처음에는 프로젝트 이름과 같은 네임스페이스 바로 아래에 배치됩니다. 이것을 Views 폴더에 넣어도 컴파일 할 수 있도록 Views 네임 스페이스로 이동합니다.
수정할 위치는 MainPage.xaml과 MainPage.xaml.cs, 잊어서는 안되는 것이 App.xaml.cs의 처음에 표시되는 페이지를 지정하는 것입니다.
첫 번째는 MainPage.xaml의 x : Class

두 번째는 MainPage.xaml.cs의 MainPage 클래스가있는 namespace

세 번째는 App.xaml.cs의 OnLaunched 함수에있는 Navigate 인수

MainPage.xaml을 고치고 나서 xaml 태그 내에서 사용하는 네임스페이스에 views와 viewmodels를 추가해 두면 편리합니다.

ViewModel 만들기
MainPage를 Views로 이동한 후 이에 해당하는 ViewModel을 만듭니다.
ViewModel에 대한 보조 클래스 만들기
ViewModel에서 View, Model에서 View로 속성의 변경을 알리기 위해서, InotifyPropertyChanged를 자주 사용하기 때문에, 이것을 구현한 클래스를 준비해 두면 상속만으로 사용할 수 있어 편리합니다.
선인의 지혜 「 Observable.cs 」를 이용합니다.
Observable.cs
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
// https://github.com/Microsoft/WindowsTemplateStudio/blob/master/templates/_composition/MVVMBasic/Project/Helpers/Observable.cs から引用
// 名前空間を修正
namespace App8.Helpers
{
public class Observable : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void Set<T>(ref T storage, T value, [CallerMemberName]string propertyName = null)
{
if (Equals(storage, value))
{
return;
}
storage = value;
OnPropertyChanged(propertyName);
}
protected void OnPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
MainPageViewModel.cs 만들기
Observable.cs를 기반으로 MainPage에 해당하는 ViewModel 클래스를 만듭니다. 초기화 함수에 View를 전달할 수 있도록 해두고, ViewModel에서 View를 참을 수 있도록 해 둡니다.
MainPageViewModel.cs
namespace App8.ViewModels
{
public class MainPageViewModel : Helpers.Observable
{
public Views.MainPage View { get; private set; } = null;
public void Initialize(Views.MainPage mainPage)
{
View = mainPage;
}
}
}
MainPage.xaml.cs 수정
MainPageViewModel 클래스와의 대응을 넣습니다. 구체적으로는 프로퍼티의 추가, ViewModel 의 초기화 코드의 호출, 데이터 문맥의 연결입니다.
MainPage.xaml.cs
using Windows.UI.Xaml.Controls;
// 空白ページの項目テンプレートについては、https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x411 を参照してください
namespace App8.Views
{
/// <summary>
/// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
/// </summary>
public sealed partial class MainPage : Page
{
public ViewModels.MainPageViewModel ViewModel { get; private set; } = new ViewModels.MainPageViewModel();
public MainPage()
{
this.InitializeComponent();
ViewModel.Initialize(this);
this.DataContext = ViewModel;
}
}
}
다국어화 (현지화)
문자열 리소스

보조 클래스
캐릭터 라인은 로컬라이즈 캐릭터 라인을 취득하기 위한 확장 메소드를 만들어 두면 편리합니다.
ResourceExtensions.cs
ResourceExtensions.cs
using System;
using System.Runtime.InteropServices;
using Windows.ApplicationModel.Resources;
// https://github.com/Microsoft/WindowsTemplateStudio/blob/master/templates/Projects/Default/Helpers/ResourceExtensions.cs から引用
// 名前空間を修正
namespace App8.Helpers
{
internal static class ResourceExtensions
{
private static ResourceLoader _resLoader = new ResourceLoader();
public static string GetLocalized(this string resourceKey)
{
return _resLoader.GetString(resourceKey);
}
}
}
여담
매번 하는 것은 수수함에 귀찮기 때문에, Microsoft의 훌륭한 템플릿 「Windows Template Studio 」를 사용하는 손도 있습니다. 고기능이므로, 코드가 복잡하게 됩니다만, Master-Detail나 설정 화면등을 처음부터 만들 수 있으므로 편리합니다.
Reference
이 문제에 관하여(UWP 앱을 MVVM으로 만들 때 먼저 할 일), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다
https://qiita.com/tanitanin/items/d6c27860b0ebdfee8797
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)
Reference
이 문제에 관하여(UWP 앱을 MVVM으로 만들 때 먼저 할 일), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://qiita.com/tanitanin/items/d6c27860b0ebdfee8797텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)