As you are following MVVM pattern to implement your application, you should notice that according to MVVM pattern guide the view should not contain any application logic:
The view is responsible for defining the structure, layout, and
appearance of what the user sees on the screen. Ideally, the view is
defined purely with XAML, with a limited code-behind that does not
contain business logic.
Replicating your FirstName
to LastName
is a part of your application logic, so you should delegate this task to your ViewModel.
Quoting MSDN again:
The view model acts as an intermediary between the view and the model,
and is responsible for handling the view logic.
which is exactly what you are trying to achieve.
So to keep things tidy, your should define FirstName
and LastName
properties in your ViewModel which will be bound to View's TextBoxes, just like you do in the code in your question:
// ViewModel
public const string FirstNamePropertyName = "FirstName";
private string _firstName = null;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
RaisePropertyChanged(FirstNamePropertyName);
}
}
public const string LastNamePropertyName = "LastName";
private string _lastName = null;
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
RaisePropertyChanged(LastNamePropertyName);
}
}
<!-- XAML -->
<Label Grid.Row="4" Grid.Column="0" Style="{StaticResource StlLblForm}" Margin="0,5">First Name:</Label>
<TextBox Grid.Row="4" MaxLength="10" Grid.Column="1" Style="{StaticResource StlTxtForm}" Text="{Binding FirstName}" Grid.ColumnSpan="2" Margin="0,1,0,11" />
<Label Grid.Row="5" Grid.Column="0" Style="{StaticResource StlLblForm}" Margin="0,5">Last Name:</Label>
<TextBox Grid.Row="5" Grid.Column="1" Style="{StaticResource StlTxtForm}" Text="{Binding LastName}" AcceptsReturn="True" Grid.ColumnSpan="2" Margin="0,1,0,11" />
While the CheckBox can be handled in two ways:
- you bind its
Checked
event to a ViewModel's command where you
manipulate your FirstName
and LastName
properties and you pass to it checkbox's IsChecked
property value as command parameter (hard way)
- you bind
IsChecked
property to the ViewModel's boolean property and
handle your logic in its setter (easy way)
So to do this the easy way:
// ViewModel
public const string CheckedPropertyName = "Checked";
private bool _checked = false;
public bool Checked
{
get
{
return _checked;
}
set
{
_checked = value;
RaisePropertyChanged(CheckedPropertyName);
// app logic is handled here
if (_checked)
{
LastName = FirstName;
}
}
}
<!-- XAML -->
<CheckBox IsChecked="{Binding Checked}" />