In this article, we will discuss the use of CommandParameters property for passing values from XAML to the data access, using XAML only mechanism.
Step 1: In the WPF project created in the previous article, add a new class file in ‘ViewModel’ folder, name it as ‘NewEmployee_Command_ViewModel.cs’. Write the following code in it.
C#
using System;
using System.Windows.Input;
using DataAccessLibrary;
namespace WPF_ADONET_EF_Commanding
{
public class CreateEmployeeCommand : ICommand
{
CreateEmployeeViewModel objCreateEmp;
public CreateEmployeeCommand(CreateEmployeeViewModel createEmp)
{
objCreateEmp = createEmp;
}
public bool CanExecute(object parameter)
{
bool action = false;
if (objCreateEmp.NewEmployee != null)
{
action = true;
}
return action;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
objCreateEmp.InsertNewEmployee(objCreateEmp.NewEmployee);
}
}
public class CreateEmployeeViewModel
{
public Employee NewEmployee { get; set; }
DataAccess objDs;
public CreateEmployeeViewModel()
{
NewEmployee = new Employee();
objDs = new DataAccess();
}
public ICommand CreateNewEmployee
{
get
{
return new CreateEmployeeCommand(this);
}
}
public void InsertNewEmployee(Employee objEmp)
{
objDs.CreateEmployee(objEmp);
}
}
}
VB.NET (Converted Code)
Imports System
Imports System.Windows.Input
Imports DataAccessLibrary
Namespace WPF_ADONET_EF_Commanding
Public Class CreateEmployeeCommand
Implements ICommand
Private objCreateEmp As CreateEmployeeViewModel
Public Sub New(ByVal createEmp As CreateEmployeeViewModel)
objCreateEmp = createEmp
End Sub
Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
Dim action As Boolean = False
If objCreateEmp.NewEmployee IsNot Nothing Then
action = True
End If
Return action
End Function
Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
objCreateEmp.InsertNewEmployee(objCreateEmp.NewEmployee)
End Sub
End Class
Public Class CreateEmployeeViewModel
Public Property NewEmployee() As Employee
Private objDs As DataAccess
Public Sub New()
NewEmployee = New Employee()
objDs = New DataAccess()
End Sub
Public ReadOnly Property CreateNewEmployee() As ICommand
Get
Return New CreateEmployeeCommand(Me)
End Get
End Property
Public Sub InsertNewEmployee(ByVal objEmp As Employee)
objDs.CreateEmployee(objEmp)
End Sub
End Class
End Namespace
Note: In the above code, the namespace is the same as the application name. This helps us to refer the class in the XAML directly, by registering this namespace in the XAML.
The above code shows Command class for managing ‘Create New Employee’ operations from XAML. The ‘CreateEmployeeViewModel’ defines the logic for making call to Insert New Employee using the Data Access Library.
Step 2: In the Views folder, add a new user control and name it as ‘EmployeeView’. This user control contains the following Xaml:
<UserControl x:Class="WPF_ADONET_EF_Commanding.EmployeeView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:viewModel="clr-namespace:WPF_ADONET_EF_Commanding"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="514">
<UserControl.Resources>
<viewModel:CreateEmployeeViewModel x:Key="EmpCreateNew"></viewModel:CreateEmployeeViewModel>
</UserControl.Resources>
<Grid x:Name="grdMain" DataContext="{Binding Source={StaticResource EmpCreateNew}}">
<Grid x:Name="grdChild" DataContext="{Binding Path=NewEmployee}">
<Grid.RowDefinitions>
<RowDefinition Height="43*" />
<RowDefinition Height="49*" />
<RowDefinition Height="47*" />
<RowDefinition Height="50*" />
<RowDefinition Height="111*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="238*" />
<ColumnDefinition Width="276*" />
</Grid.ColumnDefinitions>
<TextBlock Height="23" HorizontalAlignment="Left" Margin="11,12,0,0" Name="textBlock1" Text="EmpNo" VerticalAlignment="Top" Width="180" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="11,16,0,0" Name="textBlock2" Text="EmpName" VerticalAlignment="Top" Width="180" Grid.Row="1" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="10,16,0,0" Name="textBlock3" Text="Salary" VerticalAlignment="Top" Width="180" Grid.Row="2" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="10,14,0,0" Name="textBlock4" Text="DeptNo" VerticalAlignment="Top" Width="180" Grid.Row="3" />
<TextBox Grid.Column="1" Height="23"
HorizontalAlignment="Left" Margin="70,14,0,0"
Name="txteno" VerticalAlignment="Top"
Width="120"
Text="{Binding EmpNo,Mode=TwoWay}"/>
<TextBox Grid.Column="1" Grid.Row="1"
Height="23" HorizontalAlignment="Left"
Margin="70,13,0,0" Name="txtename"
VerticalAlignment="Top" Width="120"
Text="{Binding EmpName,Mode=TwoWay}"/>
<TextBox Grid.Column="1" Grid.Row="2" Height="23"
HorizontalAlignment="Left" Margin="70,16,0,0"
Name="txtsalary" VerticalAlignment="Top" Width="120"
Text="{Binding Salary,Mode=TwoWay}"/>
<TextBox Grid.Column="1" Grid.Row="3" Height="23"
HorizontalAlignment="Left" Margin="70,14,0,0"
Name="txtdno" VerticalAlignment="Top" Width="120"
Text="{Binding DeptNo, Mode=TwoWay}"/>
<Button Content="Create Employee" Grid.Column="1"
Grid.Row="4" Height="41" HorizontalAlignment="Left"
Margin="62,26,0,0" Name="btnCreateEmployee"
VerticalAlignment="Top" Width="144"
Command="{Binding Path=DataContext.CreateNewEmployee,ElementName=grdMain}"
CommandParameter="{Binding Path=NewEmployee,ElementName=grdChild}"/>
</Grid>
</Grid>
</UserControl>
In the above code, the gray marked code shows that first the namespace is registered in the XAML. The instance of the ‘CreateEmployeeViewModel’ is created in the resources section of the user control. The button defines Command property which is bound with the ‘CreateEmployee’ public property of the ‘CreateEmployeeViewModel’ class. This property returns an object of the ‘CreateEmployeeCommand’ class. This class defines the execution for the insert operation by calling the ‘Execute()’ method.
Grid ‘grdMain’, in the above xaml is bound with an instance of the ‘CreateEmployeeViewModel’ class using the Key defined in the resource dictionary. This initializes all objects in the constructor of the class.
The Grid,’grdChild’ is bound with the ‘NewEmployee’ public property of the ‘CreateEmployeeViewModel’ class. All Textboxes in the ‘grdChild’ grid is bound with the public properties of the Employee class. The bind mode is set to TwoWay, which will create an Employee object.
The CommandParameter property of the Button, is bound with the ‘NewEmployee’ of the ‘grdChild’. This will send the Employee object back to the command class and from this class, it will be passed to ‘InsertNewEmployee()’ method of the ‘CreateEmployeeViewModel’ and finally the object will be delivered to the Data Access Library.
Step 3: Keep the design of MainWindow.xaml similar to the one showed in Task 1 of the previous article. Open the MainWindow.Xaml.cs and write the following code in Loaded event:
C#
EmployeeView objEmpView = new EmployeeView();
grdNewEmp.Children.Add(objEmpView);
VB.NET
Dim objEmpView As New EmployeeView()
grdNewEmp.Children.Add(objEmpView)
Step 4: Run the application and insert the Employee record:
Clicking on the ‘Create Employee’ button adds a record in the database.
Conclusion: The ADO.NET EF and WPF Commanding help to build LOB applications using effective database model based programming and code less development, with commands.
The entire source code of this article can be downloaded over here
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn