Sto imparando lo schema MVVM con C #, WPF e .NET Framework 4.5.1.
Uso la struttura MVVM Light per farlo e ora ho un dubbio. Leggendo il libro Modelli MVVM di Windows 8 rivelati vedo che l'autore utilizza Event Aggregator Pattern
.
Non sono sicuro di averne bisogno, perché nel seguente ViewModel
dovrei aumentare l'evento a EventAggregator
e gestirlo sullo stesso ViewModel
.
Ecco il mio ViewModel
:
public class MainViewModel : ViewModelBase
{
private RelayCommand doLoginCommand;
/// <summary>
/// The <see cref="UserName" /> property's name.
/// </summary>
public const string UserNamePropertyName = "UserName";
private string _userName = null;
/// <summary>
/// Sets and gets the UserName property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string UserName
{
get
{
return _userName;
}
set
{
if (_userName == value)
{
return;
}
RaisePropertyChanging(UserNamePropertyName);
_userName = value;
RaisePropertyChanged(UserNamePropertyName);
}
}
/// <summary>
/// The <see cref="UserPassword" /> property's name.
/// </summary>
public const string UserPasswordPropertyName = "UserPassword";
private string _userPassword = null;
/// <summary>
/// Sets and gets the UserPassword property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string UserPassword
{
get
{
return _userPassword;
}
set
{
if (_userPassword == value)
{
return;
}
RaisePropertyChanging(UserPasswordPropertyName);
_userPassword = value;
RaisePropertyChanged(UserPasswordPropertyName);
}
}
public RelayCommand DoLoginCommand
{
get { return doLoginCommand; }
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
////if (IsInDesignMode)
////{
//// // Code runs in Blend --> create design time data.
////}
////else
////{
//// // Code runs "for real"
////}
this.doLoginCommand = new RelayCommand(ExecuteDoLogin);
}
private void ExecuteDoLogin()
{
Debug.WriteLine(_userName);
}
}
E il suo XAML:
<Window x:Class="WPFMvvmApress.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
DataContext="{Binding MainViewModel, Source={StaticResource Locator}}">
<Grid>
<StackPanel x:Name="loginPanel" HorizontalAlignment="Center" Height="159" Margin="0" VerticalAlignment="Center" Width="349">
<TextBox
x:Name="userName"
HorizontalAlignment="Left"
Height="23"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="231"
Margin="10,10,0,5"
Text="{Binding Path=UserName, Mode=TwoWay}"/>
<TextBox
x:Name="userPassword"
HorizontalAlignment="Left"
Height="23"
TextWrapping="Wrap"
VerticalAlignment="Top"
Width="231"
Margin="10,5,0,5"/>
<Button
x:Name="loginButton"
Content="Login"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Width="75"
Margin="10,5"
Command="{Binding Path=DoLoginCommand}"/>
</StackPanel>
</Grid>
</Window>
Che ne pensi?