Posted by: Zeeshan Amjad | February 27, 2010

String encoding using MVVM


We have already saw few example of MVVM here and here. But in both example we were using the Func class to implement the ICommand interface. Now we are going to see one more example of MVVM, but this time using the Action class to implement the ICommand interface. Let’s take a look at the implementation of ICommand.

  1: public class MyCommand : ICommand
  2: {
  3:     public Action Action
  4:     { get; set; }
  5: 
  6:     public MyCommand(Action action)
  7:     {
  8:         Action = action;
  9:     }
 10: 
 11:     public bool CanExecute(object parameter)
 12:     {
 13:         if (Action != null)
 14:             return true;
 15: 
 16:         return false;
 17:     }
 18: 
 19:     public void Execute(object parameter)
 20:     {
 21:         if (Action != null)
 22:         {
 23:             Action();
 24:         }
 25:     }
 26: 
 27:     public event EventHandler CanExecuteChanged
 28:     {
 29:         add { CommandManager.RequerySuggested += value; }
 30:         remove { CommandManager.RequerySuggested -= value; }
 31:     }
 32: }
 33: 

We can implement the notification using either INotifyPropertyChanged or using the dependency property. In this program we are going to use the dependency property. Here is our class to store input and output string as a dependency property.

  1: public class UserInformation : DependencyObject
  2: {
  3:     public static readonly DependencyProperty InputStringProperty =
  4:         DependencyProperty.Register("InputString", typeof(String), typeof(UserInformation));
  5: 
  6:     public static readonly DependencyProperty OutputStringProperty =
  7:         DependencyProperty.Register("OutputString", typeof(String), typeof(UserInformation));
  8: 
  9:     public static readonly DependencyProperty OutputStringLabelProperty =
 10:         DependencyProperty.Register("OutputStringLabel", typeof(String), typeof(UserInformation));
 11: 
 12:     public String InputString
 13:     {
 14:         get { return (String)GetValue(InputStringProperty); }
 15:         set { SetValue(InputStringProperty, value); }
 16:     }
 17: 
 18:     public String OutputString
 19:     {
 20:         get { return (String)GetValue(OutputStringProperty); }
 21:         set { SetValue(OutputStringProperty, value); }
 22:     }
 23: 
 24:     public String OutputStringLabel
 25:     {
 26:         get { return (String)GetValue(OutputStringLabelProperty); }
 27:         set { SetValue(OutputStringLabelProperty, value); }
 28:     }
 29: }
 30: 

Rest of the program is very much similar to the programs we have already seen. Here is complete XAML code of the program.

  1: <Window x:Class="WpfEncryption.Window1"
  2:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4:     Title="Encoding" Height="300" Width="300">
  5:     <Grid Background="Wheat">
  6:         <Grid.RowDefinitions>
  7:             <RowDefinition/>
  8:             <RowDefinition Height="2*"/>
  9:             <RowDefinition/>
 10:             <RowDefinition Height="2*"/>            
 11:             <RowDefinition/>
 12:         </Grid.RowDefinitions>
 13:         <Grid.ColumnDefinitions>
 14:             <ColumnDefinition/>
 15:             <ColumnDefinition/>
 16:         </Grid.ColumnDefinitions>
 17:         <TextBlock Margin="5" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center" Text="Input String"/>
 18:         <TextBox Margin="5" Grid.Column="0" Grid.Row="1" Grid.ColumnSpan="2" AcceptsReturn="True"
 19:                  Text="{Binding Path=UserInformation.InputString}"/>
 20:         <TextBlock Margin="5" Grid.Column="0" Grid.Row="2" VerticalAlignment="Center"
 21:                    Text="{Binding Path=UserInformation.OutputStringLabel}"/>
 22:         <TextBox Margin="5" Grid.Column="0" Grid.Row="3" Grid.ColumnSpan="2" AcceptsReturn="True" 
 23:                  Text="{Binding Path=UserInformation.OutputString}"/>
 24:         <Button Margin="5" Grid.Column="0" Grid.Row="5" Command="{Binding EncodeCommand}">
 25:             Encoding
 26:         </Button>
 27:         <Button Margin="5" Grid.Column="1" Grid.Row="5" Command="{Binding DecodeCommand}">
 28:             Decoding
 29:         </Button>
 30:     </Grid>
 31: </Window>
 32: 

And here is complete C# code of the program. Also note that we are not using the name for any control in XAML.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using System.Windows;
  6: using System.Windows.Controls;
  7: using System.Windows.Data;
  8: using System.Windows.Documents;
  9: using System.Windows.Input;
 10: using System.Windows.Media;
 11: using System.Windows.Media.Imaging;
 12: using System.Windows.Navigation;
 13: using System.Windows.Shapes;
 14: using System.ComponentModel;
 15: 
 16: namespace WpfEncryption
 17: {
 18:     /// <summary>
 19:     /// Interaction logic for Window1.xaml
 20:     /// </summary>
 21:     public partial class Window1 : Window
 22:     {
 23:         public Window1()
 24:         {
 25:             InitializeComponent();
 26: 
 27:             DataContext = new ViewModel();
 28:         }
 29:     }
 30: 
 31:     public class MyCommand : ICommand
 32:     {
 33:         public Action Action
 34:         { get; set; }
 35: 
 36:         public MyCommand(Action action)
 37:         {
 38:             Action = action;
 39:         }
 40: 
 41:         public bool CanExecute(object parameter)
 42:         {
 43:             if (Action != null)
 44:                 return true;
 45: 
 46:             return false;
 47:         }
 48: 
 49:         public void Execute(object parameter)
 50:         {
 51:             if (Action != null)
 52:             {
 53:                 Action();
 54:             }
 55:         }
 56: 
 57:         public event EventHandler CanExecuteChanged
 58:         {
 59:             add { CommandManager.RequerySuggested += value; }
 60:             remove { CommandManager.RequerySuggested -= value; }
 61:         }
 62:     }
 63: 
 64:     public class ViewModel : INotifyPropertyChanged
 65:     {
 66:         private UserInformation _userInformation;
 67:         public event PropertyChangedEventHandler PropertyChanged;
 68: 
 69:         public ViewModel()
 70:         {
 71:             _userInformation = new UserInformation();
 72:             EncodeCommand = new MyCommand(Encrypt);
 73:             DecodeCommand = new MyCommand(Decrypt);
 74:         }
 75: 
 76:         public UserInformation UserInformation
 77:         {
 78:             get 
 79:             {
 80:                 return _userInformation; 
 81:             }
 82:             set 
 83:             {
 84:                 _userInformation = value;
 85:                 RaisePropertyChanged("UserInformation");
 86:             }
 87:         }
 88: 
 89:         public ICommand EncodeCommand
 90:         { get; set; }
 91: 
 92:         public ICommand DecodeCommand
 93:         { get; set; }
 94: 
 95:         private void RaisePropertyChanged(string propertyName)
 96:         {
 97:             PropertyChangedEventHandler handler = this.PropertyChanged;
 98: 
 99:             if (handler != null)
100:             {
101:                 handler(this, new PropertyChangedEventArgs(propertyName));
102:             }
103:         }
104: 
105:         private void Encrypt()
106:         {
107:             byte[] txtByte = System.Text.Encoding.Default.GetBytes(_userInformation.InputString);
108:             _userInformation.OutputString = System.Convert.ToBase64String(txtByte);
109:             _userInformation.OutputStringLabel = "Encoded Text";
110:         }
111: 
112:         private void Decrypt()
113:         {
114:             byte[] todecodebyte = Convert.FromBase64String(_userInformation.InputString);
115:             _userInformation.OutputString = System.Text.ASCIIEncoding.ASCII.GetString(todecodebyte);
116:             _userInformation.OutputStringLabel = "Plain Text";
117:         }
118:     }
119: 
120:     public class UserInformation : DependencyObject
121:     {
122:         public static readonly DependencyProperty InputStringProperty =
123:             DependencyProperty.Register("InputString", typeof(String), typeof(UserInformation));
124: 
125:         public static readonly DependencyProperty OutputStringProperty =
126:             DependencyProperty.Register("OutputString", typeof(String), typeof(UserInformation));
127: 
128:         public static readonly DependencyProperty OutputStringLabelProperty =
129:             DependencyProperty.Register("OutputStringLabel", typeof(String), typeof(UserInformation));
130: 
131:         public String InputString
132:         {
133:             get { return (String)GetValue(InputStringProperty); }
134:             set { SetValue(InputStringProperty, value); }
135:         }
136: 
137:         public String OutputString
138:         {
139:             get { return (String)GetValue(OutputStringProperty); }
140:             set { SetValue(OutputStringProperty, value); }
141:         }
142: 
143:         public String OutputStringLabel
144:         {
145:             get { return (String)GetValue(OutputStringLabelProperty); }
146:             set { SetValue(OutputStringLabelProperty, value); }
147:         }
148:     }
149: }
150: 

This is the output of the program. It will also change the output string label.

EncodingMVVM_01

EncodingMVVM_02

Advertisements

Responses

  1. […] already saw the implementation of ICommand interface here, here and here. That was very naïve implementation. The biggest problem with this implementation […]

  2. […] from lower case to upper case here. And we also the the string encoding into base 64 using MVVM here. Let’s combine these two and create a string convertor that perform both operations and few more […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: