Prism7.2 귀속 시 유효한 접근 수식자

19461 단어 C#XamarinPrismtech

컨디션


C# : 9.0
Prism : 7.2
Xamarin.Forms : 4.4
.NET Standard 2.1

참회


냉정하게 생각해 보면 이 글은 Preism의 문제도 Xamarin의 문제도 아니다...굳이 말하자면, 문제는 자신이 C#의 언어 규범을 잊었다는 것이다.
죄송합니다.
ViewModel에서 발표된 proteted 구성원은 다른 반에서 볼 수 없기 때문에 XAML에서 왔더라도 귀속되어 있어도 접근할 수 없습니다.
엄밀히 말하면 절대 접근할 수 없는 것은 아니지만 Priism과 Xamarin은 특별히 대응하지 않고 대응할 뜻도 없다...
결론은 먼저 public으로 귀속된 ViewModel 구성원을 선포한다는 것이다.
글의 본문은 자신의 경고로 남겨야 한다.
송이경(신지현):적어도 BIND실패같은실수가 생기면...

Prism 바인딩


Preism으로 바인딩할 때 먼저 페이지와 ViewModel을 DI 컨테이너에 등록합니다.
그리고 Bindablebase를 계승한 ViewModel 옆에서 멤버를 만들고 페이지의 XAML에서{Binding メンバ}에 귀속을 적으세요.
예제)
App.xaml.cs
public partial class App
	{
		// 諸々省略
		protected override void RegisterTypes(IContainerRegistry containerRegistry)
		{
			containerRegistry.RegisterForNavigation<NavigationPage>();
			containerRegistry.RegisterForNavigation<LoginPage, LoginPageViewModel>();
		}
	}
LoginPageViewModel.cs
public class LoginPageViewModel() : BindableBase
{
	private string title;
	public string Title
	{
		get => title;
		set => SetProperty(ref title, value);
	}
	
	public LoginPageViewModel(INavigationService navigationService)
	{
		Title = "ログイン"
	}
	// 諸々省略
}
LoginPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="DeliveryInspection.Views.LoginPage"
             Title="{Binding Title}">
    
    <ContentPage.Content>
        <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
		<Label Text={Binding Text} />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
xmlns:prism="http://prismlibrary.com"
prism:ViewModelLocator.AutowireViewModel="True"
Preism6 이후라면 이거 필요 없어요.
등록하면 저절로 해줄 것 같아요.
이렇게 LogiinPage를 열면 Login 페이지의 NavigationBar에 ログイン가 표시됩니다.
아주 간단하게 만들었어요.

메시지


다음은 본론.
나는 현재 개발된 프로젝트에서 ViewModelBase를 제작하여 ViewModel이 모든 ViewModelBase를 계승하도록 했다.
ViewModelBase 코드는 다음과 같습니다.
ViewModelBase.cs
public class ViewModelBase : BindableBase, IInitialize, INavigationAware, IDestructible
	{
		protected INavigationService NavigationService { get; private set; }

		private string title;
		protected string Title
		{
			get => title;
			set => SetProperty(ref title, value);
		}

		protected ViewModelBase(INavigationService navigationService)
		{
			NavigationService = navigationService;
		}
		
		public virtual void Initialize(INavigationParameters parameters)
		{
		}

		public virtual void OnNavigatedFrom(INavigationParameters parameters)
		{
		}

		public virtual void OnNavigatedTo(INavigationParameters parameters)
		{
		}

		public virtual void Destroy()
		{
		}
	}
방금 LogiinPageView Model에서 이것을 계승하고 Title에서 로그인을 표시하도록 하고 싶습니다.
그러나 무엇을 하든 무엇을 수정하든 제목의 문자는 나타나지 않는다.
버튼의 Command 바인딩이 제대로 작동하는지 시험해 보았습니다.
Command가 ICommand에 선언하고 바인딩합니다.
LoginViewModel.cs
public class LoginPageViewModel : ViewModelBase
	{
		public ICommand GoToTabbedPageCommand { get; }

		public LoginPageViewModel(INavigationService navigationService)
			: base(navigationService)
		{
			Title = "ログイン";
			GoToTabbedPageCommand = new DelegateCommand(GoNextPageAsync);
		}

		private async void GoNextPageAsync()
		{
			await NavigationService.NavigateAsync($"/{nameof(TopPage)}");
		}
	}
LoginPage.xaml
<!-- 諸々省略 -->
<ContentPage.Content>
        <StackLayout HorizontalOptions="Center" VerticalOptions="Center">
            <Button Text="ログイン"
                    Command="{Binding GoToTabbedPageCommand}"/>
        </StackLayout>
</ContentPage.Content>
탑페이지는 생략됐지만 이렇게 되면 탑페이지가 Navigation Stack에 쌓이고 화면이 이동합니다.
내가 알고 싶은 사람은 알아야 하지만 나는 함정에 빠졌다.
프리즘 상용자의 당연한 일이라면 함정이라고 해야 할지 말아야 할지...

Proism의 Binding에는 proteted에 대응하는 멤버가 없나 봐요...


즉, ViewModelBase는 다음과 같이 수정해야 합니다.
ViewModelBase.cs
public class ViewModelBase : BindableBase, IInitialize, INavigationAware, IDestructible
	{
		// 諸々省略
		private string title;
		// protectedではなくpublic
		public string Title
		{
			get => title;
			set => SetProperty(ref title, value);
		}
		
		//protected string Title
		//{
		//	get => title;
		//	set => SetProperty(ref title, value);
		//}
	}
이렇게 하면 귀속이 순조롭게 일할 수 있습니다.
나는 상당히 긴 시간을 낭비했다.
처음부터 퍼블릭을 썼으면 좋겠는데 라이더 씨한테 프로텍트가 좋다고 해서 이번 실패 원인은 그걸 쉽게 탔기 때문이에요.
앞으로 프리즘을 사용하는 분들은 주의하세요.
(Xamarin.Forms도 마찬가지)
퍼블릭 멤버를 묶는 방법 이외의 방법이 있다면!만약 이런 정보가 있다면, 나에게 알려줄 수 있다면 나는 매우 기쁠 것이다...
지금까지 프리즘 초보자의 프리즘에서 주의해야 할 사항입니다.

좋은 웹페이지 즐겨찾기