Должны ли эти члены быть в модели?и если да, то как? - PullRequest
0 голосов
/ 28 сентября 2018

Я новичок в WPF и Prism, поэтому сейчас пытаюсь разобраться в самых простых вещах.Мой маленький эксперимент выглядит следующим образом:

enter image description here

У меня есть Views\Registration.xaml, который выглядит так:

<UserControl x:Class="Configurator.Views.Registration"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Column="0" Grid.Row="0" Content="Email:" HorizontalContentAlignment="Right" Margin="6"/>
        <TextBox Grid.Column="1" Grid.Row="0" x:Name="email" Margin="6" Text="{Binding Email}"/>
        <Label Grid.Column="0" Grid.Row="1" Content="Password:" HorizontalContentAlignment="Right" Margin="6"/>
        <PasswordBox Grid.Column="1" Grid.Row="1" x:Name="password" Margin="6" />
        <Label Grid.Column="0" Grid.Row="2" Content="Password Confirmation:" HorizontalContentAlignment="Right" Margin="6"/>
        <PasswordBox Grid.Column="1" Grid.Row="2" x:Name="passwordConfirmation" Margin="6"/>
        <Button Grid.Column="1" Grid.Row="3" Content="Register" HorizontalAlignment="Left" Margin="6" Padding="6,2" Command="{Binding RegisterCommand}"/>
    </Grid>
</UserControl>

а затем ViewModels\RegistrationViewModel.cs, который выглядит следующим образом:

namespace Configurator.ViewModels {
    public class RegistrationViewModel : BindableBase {
        private string _email;
        public string Email {
            get { return _email; }
            set { SetProperty(ref _email, value); }
        }

        private string _password;
        public string Password {
            get { return _password; }
            set { SetProperty(ref _password, value); }
        }

        private string _passwordConfirmation;
        public string PasswordConfirmation {
            get { return _passwordConfirmation; }
            set { SetProperty(ref _passwordConfirmation, value); }
        }

        public DelegateCommand RegisterCommand { get; private set; }

        public RegistrationViewModel() {
            Console.WriteLine("RegistrationViewModel");
            RegisterCommand = new DelegateCommand(Register);
        }

        private void Register() {
            Console.WriteLine("Registering");
            Console.WriteLine($"Email: {Email}");
            Console.WriteLine($"Password: {Password}");
            Console.WriteLine($"Password Confirmation: {PasswordConfirmation}");
        }
    }
}

Должны ли Email, Password и PasswordConfirmation войти в модель при следовании за MVVM?Если это должно войти в модель, как проводка сделана?Я не могу найти никаких примеров.

Ответы [ 3 ]

0 голосов
/ 28 сентября 2018

Поскольку вы используете MVVM, свойства должны быть в модели.Затем вы создаете свойство этой Модели в вашей ViewModel, чтобы оно вызывало PropertyChanged-Event из INotifyPropertyChanged.

В представлении вы затем привязываете имена элементов Model-Property из вашей ViewModel.

Тогда вам просто нужно решить, хотите ли вы, чтобы ваша Модель также реализовывала INotifyPropertyChanged, или вы найдете другой способ.

0 голосов
/ 28 сентября 2018

Ваша ViewModel и XAML в порядке.Да, вы должны предоставить электронную почту, пароль и т. Д. Как часть ViewModel.

Отсутствующая часть в вашем примере - это привязка ViewModel к пользовательскому интерфейсу.Этого можно добиться, объявив об этом в своем XAML или в конструкторе на странице с выделенным кодом, у вас может быть

public Registration(RegistrationViewModel model)
{
    DataContext = model;
}

Какую проводку вы запрашиваете, потому что все это выглядит довольно хорошо для меня.

0 голосов
/ 28 сентября 2018

Ваша реализация выглядит хорошо для меня, т.е. вы привязываетесь к свойствам модели представления.

Иногда люди склонны называть модели представлением «моделями», но фактическая модель в этом случае будет представлена ​​службой, которая выполняет фактическую регистрацию.

Вы можете внедрить модель представления в интерфейс, который реализует эта служба, и затем вызвать метод службы через этот интерфейс в вашем методе Register(), например:

public class RegistrationViewModel : BindableBase
{
    ...
    private readonly IRegistrationService _registrationService;
    public RegistrationViewModel(IRegistrationService registrationService)
    {
        _registrationService = registrationService ?? throw new ArgumentNullException(nameof(registrationService));
        RegisterCommand = new DelegateCommand(Register);
    }

    private void Register()
    {
        _registrationService.Register(...);
    }
}
...