Posted by: Zeeshan Amjad | November 26, 2013

Logical Multivalue Converter with LINQ


We just studied the logical multivalve converter here. Now we are going to do the same thing but instead of doing it manually traversing every values and apply the “AND” or “OR” logical operation, we can achieve the same thing with LINQ. We can use the Extension methods “All” and “Any” defined for IEnumerable type to do the same thing.

Here is an updated version of our Logical And converter.

Code Snippet
using System.Linq;

namespace MyConverter
{
    using System.Windows.Data;

    [ValueConversion(typeof(bool), typeof(bool))]
    public class AndConverter : IMultiValueConverter
    {
        public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return values.Cast<bool>().All(value => value);
        }

        public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}

 

Similarly here is an updated version of Logical Or operator.

Code Snippet
using System.Linq;

namespace MyConverter
{
    using System.Windows.Data;

    [ValueConversion(typeof(bool), typeof(bool))]
    public class OrConverter : IMultiValueConverter
    {
        public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return values.Cast<bool>().Any(value => value);
        }

        public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}

 

Rest of the code of this application and out put is exactly the same as previous program. Here is our C# code.

 

Code Snippet
namespace MyConverter
{
    using System.Linq;
    using System.ComponentModel;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MyConditions();
        }
    }

    public class MyConditions : INotifyPropertyChanged
    {
        private bool _condition1;

        #region NotifyPropertyChanged Methods

        public void RaisePropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public bool Condition1
        {
            get
            {
                return _condition1;
            }

            set
            {
                _condition1 = value;
                RaisePropertyChanged("Condition1");
            }
        }

        public bool Condition2
        {
            get
            {
                return _condition1;
            }

            set
            {
                _condition1 = value;
                RaisePropertyChanged("Condition2");
            }
        }

        public bool Condition3
        {
            get
            {
                return _condition1;
            }

            set
            {
                _condition1 = value;
                RaisePropertyChanged("Condition3");
            }
        }

        public bool Condition4
        {
            get
            {
                return _condition1;
            }

            set
            {
                _condition1 = value;
                RaisePropertyChanged("Condition4");
            }
        }
    }
}

 

And here is our XAML.

Code Snippet
<Window x:Class="MyConverter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:MyConverter"
        Title="And Or Converters" Height="300" Width="400">
    <Window.Resources>
        <local:AndConverter x:Key="AndConverter"/>
        <local:OrConverter x:Key="OrConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <CheckBox Grid.Row="0" VerticalAlignment="Center"
                  Name="Condition1" Margin="5" IsChecked="{Binding Condition1}"
                  Content="Conditin 1"/>
        <CheckBox Grid.Row="1" Grid.Column="0" VerticalAlignment="Center"
                  Name="Condition2" Margin="5" IsChecked="{Binding Condition2}"
                  Content="Conditin 2"/>
        <CheckBox Grid.Row="2" Grid.Column="0" VerticalAlignment="Center"
                  Name="Condition3" Margin="5" IsChecked="{Binding Condition3}"
                  Content="Conditin 3"/>
        <CheckBox Grid.Row="3" Grid.Column="0" VerticalAlignment="Center"
                  Name="Condition4" Margin="5" IsChecked="{Binding Condition4}"
                  Content="Conditin 4"/>
        <TextBox Grid.Row="4" Grid.Column="0" VerticalAlignment="Center"
                   Margin="5" Text="And Value Converter">
            <TextBox.IsEnabled>
                <MultiBinding Converter="{StaticResource AndConverter}">
                    <Binding Path="Condition1"/>
                    <Binding Path="Condition2"/>
                    <Binding Path="Condition3"/>
                    <Binding Path="Condition4"/>
                </MultiBinding>
            </TextBox.IsEnabled>
        </TextBox>
        <TextBox Grid.Column="1" Grid.Row="4" VerticalAlignment="Center"
                   Margin="5" Text="Or Value Converter">
            <TextBox.IsEnabled>
                <MultiBinding Converter="{StaticResource OrConverter}">
                    <Binding Path="Condition1"/>
                    <Binding Path="Condition2"/>
                    <Binding Path="Condition3"/>
                    <Binding Path="Condition4"/>
                </MultiBinding>
            </TextBox.IsEnabled>
        </TextBox>
    </Grid>
</Window>

 

Here is an output of the program.

LogicalMultiValueConverter

Advertisements
Posted by: Zeeshan Amjad | November 15, 2013

Logical Multi value Converter


During one of my project, I came across a situation where I should enable or disable a control based on not one condition, but more than one conditions. For example, do not enable the submit button until user input all the required information. Or do not enable the button to move the next page of the wizard until you select all the required information from all the combo boxes and check boxes in the current screen.

As like other things, this can be done in different ways in WPF. I decided to use multi value converter for this purpose. The reason is because it is very lightweight and can be make generic enough to reuse and unlike markup extension can be applied at run time when the value of properties changes.

We already have an example of not converter here. There is only one operand to not operator, therefore we can implement it using IValueConverter interface. However, And, Or, operator needs at least two operators, therefore it has to be IMultiValueConverter interface.

Making “And” and “Or” logical operator are very straight forward. Here is a code for “And Converter”.

Code Snippet
namespace MyConverter
{
    using System.Windows.Data;

    [ValueConversion(typeof(bool), typeof(bool))]
    public class AndConverter : IMultiValueConverter
    {
        public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool result = true;

            foreach (var item in values)
            {
                bool value = (bool)item;

                if (!value)
                {
                    return false;
                }
            }

            return result;
        }

        public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}

 

The “Or Converter” is also very similar. Here is a code for “Or Converter”.

 

Code Snippet
namespace MyConverter
{
    using System.Windows.Data;

    [ValueConversion(typeof(bool), typeof(bool))]
    public class OrConverter : IMultiValueConverter
    {
        public object Convert(object[] values, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            bool result = false;

            foreach (var item in values)
            {
                bool value = (bool)item;

                if (value)
                {
                    return true;
                }
            }

            return result;
        }

        public object[] ConvertBack(object value, System.Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new System.NotImplementedException();
        }
    }
}

 

Now how we are going to use it. Its usage is very similar to any other converter. First creates and object of this class, usually in XAML in resource section then pass bind the conditions to it. Here is a usage of it.

Code Snippet
<TextBox Grid.Row="4" VerticalAlignment="Center"
           Margin="5" Text="And Value Converter">
    <TextBox.IsEnabled>
        <MultiBinding Converter="{StaticResource andConverter}">
            <Binding Path="Condition1"/>
            <Binding Path="Condition2"/>
            <Binding Path="Condition3"/>
            <Binding Path="Condition4"/>
        </MultiBinding>
    </TextBox.IsEnabled>
</TextBox>

 

Here we bind the enable property of TextBox to 4 conditions. Because we are using And converter, therefore the textbox will enable if all the condition will be true. These conditions can be set using any other UI element, some business logic or even based on other conditions. Usage of Or converter is also very similar.

Here is complete XAML of this simple program.

Code Snippet
<Window x:Class="MyConverter.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:MyConverter"
        Title="And Or Converters" Height="300" Width="400">
    <Window.Resources>
        <local:AndConverter x:Key="andConverter"/>
        <local:OrConverter x:Key="orConverter"/>
    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <CheckBox Grid.Row="0" VerticalAlignment="Center"
                  Name="condition1" Margin="5" IsChecked="{Binding Condition1}"
                  Content="Conditin 1"/>
        <CheckBox Grid.Row="1" VerticalAlignment="Center"
                  Name="condition2" Margin="5" IsChecked="{Binding Condition2}"
                  Content="Conditin 2"/>
        <CheckBox Grid.Row="2" VerticalAlignment="Center"
                  Name="condition3" Margin="5" IsChecked="{Binding Condition3}"
                  Content="Conditin 3"/>
        <CheckBox Grid.Row="3" VerticalAlignment="Center"
                  Name="condition4" Margin="5" IsChecked="{Binding Condition4}"
                  Content="Conditin 4"/>
        <TextBox Grid.Row="4" VerticalAlignment="Center"
                   Margin="5" Text="And Value Converter">
            <TextBox.IsEnabled>
                <MultiBinding Converter="{StaticResource andConverter}">
                    <Binding Path="Condition1"/>
                    <Binding Path="Condition2"/>
                    <Binding Path="Condition3"/>
                    <Binding Path="Condition4"/>
                </MultiBinding>
            </TextBox.IsEnabled>
        </TextBox>
        <TextBox Grid.Column="1" Grid.Row="4" VerticalAlignment="Center"
                   Margin="5" Text="Or Value Converter">
            <TextBox.IsEnabled>
                <MultiBinding Converter="{StaticResource orConverter}">
                    <Binding Path="Condition1"/>
                    <Binding Path="Condition2"/>
                    <Binding Path="Condition3"/>
                    <Binding Path="Condition4"/>
                </MultiBinding>
            </TextBox.IsEnabled>
        </TextBox>
    </Grid>
</Window>

 

And here is a C# code of the program.

Code Snippet
namespace MyConverter
{
    using System.ComponentModel;
    using System.Windows;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new MyConditions();
        }
    }

    public class MyConditions : INotifyPropertyChanged
    {
        private bool condition1;
        private bool condition2;
        private bool condition3;
        private bool condition4;

        #region NotifyPropertyChanged Methods

        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        public bool Condition1
        {
            get
            {
                return this.condition1;
            }

            set
            {
                this.condition1 = value;
                this.RaisePropertyChanged("Condition1");
            }
        }

        public bool Condition2
        {
            get
            {
                return this.condition1;
            }

            set
            {
                this.condition1 = value;
                this.RaisePropertyChanged("Condition2");
            }
        }

        public bool Condition3
        {
            get
            {
                return this.condition1;
            }

            set
            {
                this.condition1 = value;
                this.RaisePropertyChanged("Condition3");
            }
        }

        public bool Condition4
        {
            get
            {
                return this.condition1;
            }

            set
            {
                this.condition1 = value;
                this.RaisePropertyChanged("Condition4");
            }
        }
    }
}

 

Here is an output of the program.

LogicalMultiValueConverter

Posted by: Zeeshan Amjad | September 28, 2013

Editable ComboBox in MVVM


Creating an editable combo box in WPF is not very difficult, just set the IsEditable property to true. What makes it interesting is when we are trying to add a new item in the combo box that is not a part of it before using data binding or MVVM pattern. In other words doing it without any code behind.

Let’s first step to create a MVVM application using editable combo box without adding any new item in it. It is quite straight forward task.

This is simple and standard view model with two properties. First one is an observable collection stored the list of cities and the other one is selected city.

Code Snippet
public class ViewModel : INotifyPropertyChanged
{
    private ObservableCollection<string> cities = new ObservableCollection<string>();
    private string selectedItem;

    public ViewModel()
    {
        this.Cities.Add("Boston");
        this.Cities.Add("Los Angeles");
        this.cities.Add("Frederick");
        this.cities.Add("Houston");

        this.SelectedCity = "Boston";
    }

    public ObservableCollection<string> Cities
    {
        set
        {
            this.cities = value;
            this.RaisePropertyChanged("Cities");
        }
        get
        {
            return this.cities;
        }
    }

    public string SelectedCity
    {
        set
        {
            this.selectedItem = value;
            this.RaisePropertyChanged("SelectedCity");
        }
        get
        {
            return this.selectedItem;
        }
    }

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

 

The reason to create a selected city property is two fold. First we want to show the selected item in the textbox (or any other control). But the most important one is when we are going to add the functionality of add items in the combo box, then it will be more useful, because we don’t only add the items in the combo box, but also set that value as a selected item. Obviously it doesn’t make sense that first user entered a new entry, then select it from the combo box, it should be one step.

Now lets see the fun part i.e. going to add a new city in the editable combo box. To do this we are going to use the Text property of the combo box. We already used the ItemsSource and SelectedItems property and this time we are going to introduce one more property in my view model class to bind with TextProperty of the combo box.

And here rubber meets the road. We will add the new entry in the city collection. In addition to this, we return the selected city as a getter of that property, because there is no field to backup this. It would be something like this.

Code Snippet
public string NewCity
{
    set
    {
        if (!string.IsNullOrEmpty(value))
        {
            this.Cities.Add(value);
            this.SelectedCity = value;
        }
    }
    get
    {
        return this.SelectedCity;
    }
}

 

Here is a complete XAML of our program.

Code Snippet
<Window x:Class="WpfEditableCombo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="Editable ComboxBox" Height="300" Width="400">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ComboBox Grid.Row="0" Margin="5" VerticalAlignment="Center" IsEditable="True"
                  ItemsSource="{Binding Cities}"
                  SelectedItem="{Binding SelectedCity}"
                  Text="{Binding NewCity, UpdateSourceTrigger=LostFocus}"/>
        <TextBox Grid.Row="1" Margin="5" VerticalAlignment="Center"
                   Text="{Binding SelectedCity}"/>
    </Grid>
</Window>

 

The only important thing to note here is the UpgradeSourceTrigger property. We set it to LostFocus, so it will call the setter of NewItems property only when we lost the focus from the combobox. In other words, we only add items in the collection when we are done with out editing. But you should have another control there to get the focus and that is exactly the reason I have TextBox, not TextBlock here.

Here is the initial screen shot of the program.

EditableCombo_01

And here is a screen shot after adding “New York” in the combo box.

EditableCombo_02

Posted by: Zeeshan Amjad | August 23, 2013

Using Timer in MVVM


Currently I came across a problem where I am supposed to use timer in my MVVM based application. Initially i was little concern that where should i put the event handler to response the timer tick, but eventually settled up to write event handler in my ViewModel. By making timer tick event handler in ViewModel, we are not making it UI specific or even UI aware anyway. Once i settled this then rest of the exercise is very straight forward.

Let’s first do some infrastructure work. Here is my simple implementation of ICommand interface. This is not a general purpose implementation of ICommand interface, because we simply ignore the predicate and command parameter, but for this small project this is enough. You can see the more general implementation here.

Code Snippet
public class RelayCommand : ICommand
{
    private Action Function;
    private Func<bool> Predicate;

    public RelayCommand(Action Function)
    {
        this.Function = Function;
    }

    public RelayCommand(Action Function, Func<bool> Predicate)
    {
        this.Function = Function;
        this.Predicate = Predicate;
    }

    #region NotifyPropertyChanged Methods

    public bool CanExecute(object parameter)
    {
        if (this.Predicate != null)
        {
            return this.Predicate();
        }

        return true;
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        if (this.Function != null)
        {
            this.Function();
        }
    }

    #endregion
}

 

Now comes the fun part, ViewModel. In our ViewModel, i introduced four properties. Two of them are ICommand type properties to start and stop the timer and one is Text property to display the current time on the screen. I also made the duration property although currently we set its value 1000 and not setting it, but it would be useful in a program where we even want to set the duration of our time tick.

The interesting part is to set the event handler in out start timer method.

Code Snippet
public void StartTimer()
{
    timer = new DispatcherTimer();
    timer.Interval = TimeSpan.FromMilliseconds(this.Duration);
    timer.Tick += new EventHandler(TimerTick);
    timer.Start();
}

 

In our event handler, we simply set the Text to current time. Here is complete implementation of our ViewModel.

Code Snippet
public class TimerViewModel : INotifyPropertyChanged
{
    private int duration;
    private string text;
    private DispatcherTimer timer = null;

    public TimerViewModel()
    {
        this.Duration          = 1000;
        this.Text              = DateTime.Now.ToString("HH:mm:ss tt");
        this.StartTimerCommand = new RelayCommand(this.StartTimer);
        this.StopTimerCommand  = new RelayCommand(this.StopTimer);
    }

    #region Properties
    
    public int Duration
    {
        get
        {
            return this.duration;
        }
        set
        {
            this.duration = value;
            RaisePropertyChanged("Duration");
        }
    }

    public string Text
    {
        get
        {
            return this.text;
        }
        set
        {
            this.text = value;
            RaisePropertyChanged("Text");
        }
    }

    public ICommand StartTimerCommand
    {
        get;
        set;
    }

    public ICommand StopTimerCommand
    {
        get;
        set;
    }

    #endregion

    #region NotifyPropertyChanged Methods

    public event PropertyChangedEventHandler PropertyChanged;

    public void RaisePropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = this.PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion

    public void StartTimer()
    {
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(this.Duration);
        timer.Tick += new EventHandler(TimerTick);
        timer.Start();
    }

    public void StopTimer()
    {
        if (timer != null)
        {
            timer.Stop();
            timer = null;
        }
    }

    private void TimerTick(object send, EventArgs e)
    {
        this.Text = DateTime.Now.ToString("HH:mm:ss tt");
    }
}

 

Our XAML code is very straight forward, we just do the binding with Button and TextBlock. Here is our XAML code.

Code Snippet
<Window x:Class="WpfMvvmTimer.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="Timer ViewModel" Height="200" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="45"/>
        </Grid.RowDefinitions>
        <TextBlock Grid.Column="0" Grid.Row="0" Grid.ColumnSpan="2" Margin="5"
                   VerticalAlignment="Center" HorizontalAlignment="Center"
                   FontSize="32" FontWeight="Bold"
                   Text="{Binding Text}"/>
        <Button Grid.Column="0" Grid.Row="1" Margin="5"
                Command="{Binding StartTimerCommand}"
                Content="Start Timer"/>
        <Button Grid.Column="1" Grid.Row="1" Margin="5"
                Command="{Binding StopTimerCommand}"
                        Content="Stop Timer"/>
        </Grid>
</Window>

 

In our main, we simply create an object of our ViewMode and set the DataContext property to our view Model. Here is a complete C# code of our project

Code Snippet
namespace WpfMvvmTimer
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Input;
    using System.Windows.Threading;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = new TimerViewModel(); ;
        }
    }

    public class TimerViewModel : INotifyPropertyChanged
    {
        private int duration;
        private string text;
        private DispatcherTimer timer = null;

        public TimerViewModel()
        {
            this.Duration          = 1000;
            this.Text              = DateTime.Now.ToString("HH:mm:ss tt");
            this.StartTimerCommand = new RelayCommand(this.StartTimer);
            this.StopTimerCommand  = new RelayCommand(this.StopTimer);
        }

        #region Properties
        
        public int Duration
        {
            get
            {
                return this.duration;
            }
            set
            {
                this.duration = value;
                RaisePropertyChanged("Duration");
            }
        }

        public string Text
        {
            get
            {
                return this.text;
            }
            set
            {
                this.text = value;
                RaisePropertyChanged("Text");
            }
        }

        public ICommand StartTimerCommand
        {
            get;
            set;
        }

        public ICommand StopTimerCommand
        {
            get;
            set;
        }

        #endregion

        #region NotifyPropertyChanged Methods

        public event PropertyChangedEventHandler PropertyChanged;

        public void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

        public void StartTimer()
        {
            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(this.Duration);
            timer.Tick += new EventHandler(TimerTick);
            timer.Start();
        }

        public void StopTimer()
        {
            if (timer != null)
            {
                timer.Stop();
                timer = null;
            }
        }

        private void TimerTick(object send, EventArgs e)
        {
            this.Text = DateTime.Now.ToString("HH:mm:ss tt");
        }
    }

    public class RelayCommand : ICommand
    {
        private Action Function;
        private Func<bool> Predicate;

        public RelayCommand(Action Function)
        {
            this.Function = Function;
        }

        public RelayCommand(Action Function, Func<bool> Predicate)
        {
            this.Function = Function;
            this.Predicate = Predicate;
        }

        #region NotifyPropertyChanged Methods

        public bool CanExecute(object parameter)
        {
            if (this.Predicate != null)
            {
                return this.Predicate();
            }

            return true;
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            if (this.Function != null)
            {
                this.Function();
            }
        }

        #endregion
    }
}

 

When we run the program it shows the current time and do nothing. But if we press the Start Timer button, then it will updating the current time every second. Here is an output of the program.

TimerViewModel

Posted by: Zeeshan Amjad | July 31, 2013

Using Mediator to communicate between user controls: Part 8


The mediator pattern we created here works quite well for most of my scenario where i am suppose to use int message not string messages. Changing the class is not a big deal, i can easily change the source of Mediator class to use int and create Dictionary of int instead of string. But this raise a question, what if in future i want to use a different type? Do I have to do it again. Why not make it such a way that it can be used with more than one type without changing the code, or at best minimal changes of code.

I decided to make message generic just like i did with Action parameter. Its quite simple solution and can be done in few minutes. Here is a new version of Mediator class that uses generic messages.

Code Snippet
namespace MVVMBase
{
    using System;
    using System.Collections.Generic;

    public sealed class Mediator<TMessage>
    {
        private Dictionary<TMessage, List<WeakReferenceWrapper>> actions =
             new Dictionary<TMessage, List<WeakReferenceWrapper>>();

        public Mediator()
        {
        }

        public void Register<TParameter>(TMessage message, object receiver, Action<TParameter> action)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            lock (this.actions)
            {
                if (!this.actions.ContainsKey(message))
                {
                    this.actions[message] = new List<WeakReferenceWrapper>();
                }

                this.actions[message].Add(new WeakReferenceWrapper(receiver, action));
            }
        }

        public void Unregister<TParameter>(TMessage message, object receiver, Action<TParameter> action)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            lock (this.actions)
            {
                if (this.actions.ContainsKey(message))
                {
                    List<WeakReferenceWrapper> actionlist = this.actions[message];

                    actionlist.Remove(new WeakReferenceWrapper(receiver, action));

                    if (actionlist.Count == 0)
                    {
                        this.actions.Remove(message);
                    }
                }
            }
        }

        public void Send<TParameter>(TMessage message, TParameter parameter)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            lock (this.actions)
            {
                if (this.actions.ContainsKey(message))
                {
                    List<WeakReferenceWrapper> actionslist = this.actions[message];

                    foreach (var action in actionslist)
                    {
                        action.Action.DynamicInvoke(parameter);
                    }
                }
            }
        }
    }
}

So far so good, but now I have to change the Mediator property too in all of my ViewModel and UserControl classes to use the type. Let’s first create a Mediator object with additional information.

Code Snippet
Mediator = new Mediator<int>();

Mediator.Register<object>(1, myvm, myvm.Notify);

 

And here is a change we are suppose to do in ViewModel or UserControl code behing class.

Code Snippet
public Mediator<int> Mediator
{
    get;
    set;
}

 

Remember the type should be the same, otherwise you will get a compilation error. Let’s force it by making a contract that every class that need to send message or be notified used a proper signature by introducing interface. We can make an interface that does this. Here is a code of our interface

Code Snippet
namespace MVVMBase
{
    interface IMediator<TMessage, TParameter>
    {
        Mediator<TMessage> Mediator
        {
            get;
            set;
        }

        void Send(TMessage message, TParameter parameter);

        void Notify(TParameter parameter);
    }
}

 

In this way we also document that which classes are taking part of this approach. Here is an example of one class that implement this interface.

Code Snippet
public class SettingsViewModel : ViewModelBase, IMediator<int, object>
{

    // other stuff

    public Mediator<int> Mediator
    {
        get;
        set;
    }

    public ICommand GetSettingsCommand
    {
        get;
        set;
    }

    public void Send(int message, object o)
    {
        Mediator.Send<object>(message, o);
    }

    public void Notify(object o)
    {

    }

    private void GetSettings()
    {
        Send(1, "testmessage");
    }
}

 

But this will create one interesting problem. Now we can select the message type, but our message is restricted. If we want to pass different types of messages, then we have to implement IMediator interface with different second generic parameter.

Let’s remove the second parameter from IMediator interface and make it generic only for message type. In this case we have to modify the Send and Nofity methods and and make those generic. Here is updated version of our IMediator interface.

Code Snippet
namespace MVVMBase
{
    public interface IMediator<TMessage>
    {
        Mediator<TMessage> Mediator
        {
            get;
            set;
        }

        void Send<TParameter>(TMessage message, TParameter parameter);

        void Notify<TParameter>(TParameter parameter);
    }
}

 

Here is a usage of our new IMediator interface

Code Snippet
namespace ADFDesktopTool
{
    using System.Collections.ObjectModel;
    using System.Windows.Input;
    using MVVMBase;

    public class SettingsViewModel : ViewModelBase, IMediator<int>
    {
        // other stuff

        public Mediator<int> Mediator
        {
            get;
            set;
        }

        public void Send<TParameter>(int message, TParameter arg)
        {
            Mediator.Send<TParameter>(message, arg);
        }

        public void Notify<TParameter>(TParameter args)
        {

        }

    }
}

 

Let’s make one small change in our Mediator class. Currently our Mediator class can register any class. Let’s make it more specific to register classes which implement IMediator interface only. Here is a new version of our Mediator class.

Code Snippet
namespace MVVMBase
{
    using System;
    using System.Collections.Generic;

    public sealed class Mediator<TMessage>
    {
        private Dictionary<TMessage, List<WeakReferenceWrapper>> actions =
             new Dictionary<TMessage, List<WeakReferenceWrapper>>();

        public Mediator()
        {
        }

        public void Register<TParameter>(TMessage message, IMediator<TMessage> receiver, Action<TParameter> action)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            lock (this.actions)
            {
                if (!this.actions.ContainsKey(message))
                {
                    this.actions[message] = new List<WeakReferenceWrapper>();
                }

                this.actions[message].Add(new WeakReferenceWrapper(receiver, action));
            }
        }

        public void Unregister<TParameter>(TMessage message, IMediator<TMessage> receiver, Action<TParameter> action)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            lock (this.actions)
            {
                if (this.actions.ContainsKey(message))
                {
                    List<WeakReferenceWrapper> actionlist = this.actions[message];

                    actionlist.Remove(new WeakReferenceWrapper(receiver, action));

                    if (actionlist.Count == 0)
                    {
                        this.actions.Remove(message);
                    }
                }
            }
        }

        public void Send<TParameter>(TMessage message, TParameter parameter)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            lock (this.actions)
            {
                if (this.actions.ContainsKey(message))
                {
                    List<WeakReferenceWrapper> actionslist = this.actions[message];

                    foreach (var action in actionslist)
                    {
                        action.Action.DynamicInvoke(parameter);
                    }
                }
            }
        }
    }
}

 

This is more powerful version of mediator than previous version can accept any type of message type and define contract to use with mediator.

The output of the program is same as previous program.

mediator_02_output


We already saw how to implement INotifyPropertyChanged here. Since beginning this approach has a problem of hardcoded string, i.e. we have to pass the name of the property as a string. Although the name of the property can be retrieved by using some expression or reflection, but that is not only complicate code , but also make it little slower.

Finally in .Net 4.5 Microsoft introduced one simple way to avoid passing the string while implementing INotifyPropertyChanged interface and the solution is CallerMemberName attribute. If we specify this attribute with the parameter of a function, then it will be populated with the caller function. Along with this, Microsoft also introduced CallerFilePathAttribute and CallerLineNumberAttribute, which are self explanatory.

Now we have to change our RaisePropertyChanged method little bit to use this new feature.

Code Snippet
#region NotifyPropertyChanged Methods

public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
    PropertyChangedEventHandler handler = this.PropertyChanged;

    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public event PropertyChangedEventHandler PropertyChanged;

#endregion

 

Now the propertyName parameter takes the default value, therefore we can simply ignore in the properties implementation and can never be out of sync.

Here is a complete XAML code of the project.

Code Snippet
<Window x:Class="NotifyPropertyChangeDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="INotifyPropertyChange" Height="300" Width="400">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Margin="5" Grid.Column="0" Grid.Row="0" VerticalAlignment="Center">
            Enter First Number
        </TextBlock>
        <TextBox Margin="5" Grid.Column="1" Grid.Row="0"
                 VerticalAlignment="Center" Text="{Binding First}"/>
        <TextBlock Margin="5" Grid.Column="0" Grid.Row="1" VerticalAlignment="Center">
            Enter Second Number
        </TextBlock>
        <TextBox Margin="5" Grid.Column="1" Grid.Row="1"
                 VerticalAlignment="Center" Text="{Binding Second}"/>
        <TextBlock Margin="5" Grid.Column="0" Grid.Row="2" VerticalAlignment="Center">
            The number of primes in between theese numbare are
        </TextBlock>
        <TextBlock Margin="5" Grid.Column="1" Grid.Row="2"
                   VerticalAlignment="Center" Text="{Binding Result}"/>
        <Button Margin="5" Grid.Column="0" Grid.Row="3" Click="Button_Click">
            Exit
        </Button>
        <Button Margin="5" Grid.Column="1" Grid.Row="3" Click="Button_Click_1">
            Calculate
                </Button>
    </Grid>
</Window>

 

And here is a complete C# code of the project

Code Snippet
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Windows;

namespace NotifyPropertyChangeDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Data data = new Data();

        public MainWindow()
        {
            InitializeComponent();

            DataContext = data;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            int count = 0;

            for (int i = data.First; i <= data.Second; i++)
            {
                if (isPrime(i))
                {
                    count++;
                }
            }

            data.Result = count;
        }

        private bool isPrime(int no)
        {
            if (no < 2)
                return false;

            for (int i = 2; i < no / 2; i++)
            {
                if (no % i == 0)
                    return false;
            }

            return true;
        }
    }

    public class Data : INotifyPropertyChanged
    {
        private int first;
        private int second;
        private int result;

        public int First
        {
            get
            {
                return first;
            }
            set
            {
                first = value;
                RaisePropertyChanged();
            }
        }

        public int Second
        {
            get
            {
                return second;
            }
            set
            {
                second = value;
                RaisePropertyChanged();
            }
        }

        public int Result
        {
            get
            {
                return result;
            }
            set
            {
                result = value;
                RaisePropertyChanged();
            }
        }

        #region NotifyPropertyChanged Methods

        public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

    }
}

 

This is the output of a program.

CallerMemberNameOutput

Posted by: Zeeshan Amjad | July 4, 2013

Exponential Moving Average using Mindscape


Moving average is very common technique in finance and technical analysis. In simple moving average, we simply select the window size and calculate the average of dataset in that window and then keep moving the window. Therefore it is also known as rolling average or running average or simple moving average (SMA). Usually we are calculating SMA for historical price, volume or other stock data. Here is its formula.

SMA_1

The other common averages used in finance and technical analysis are weighted moving average (WMA) and exponential moving average (EMA) or exponentially weighted moving average (EWMA). The purpose of EMA is to give the higher weight of today’s price (volume or other stock data) and lower weight to older data.

The main difference between these two are in weighted moving average, the weight assigned to data are decrease with same interval making athematic progression. However, in case of exponential moving average the weight assigned to the data decrease exponentially. It means that older data in WMA has higher weight than the same data in EMA. However it is quite possible that the weight of older data in WMA is zero but there is little weight in EMA.

Let’s take a look at graphical representation of both of these to see the difference. Here is a formula to calculate the weight of WMA for different date.

WMA_Weight

Here “Wi” is the weight for ith day and n is the windows size. Let’s try to draw the graph of 20 days weight calculated when n is equal to 12.

WMA_Weight_Graph

Here is a formula to calculate the weight of EMA for different date.

EMA_Weight

Here “Wi” is the weight for the ith day and n is the window size. Here is a graph of 20 days weight calculatged when n is equal to 12.

EMA_Weight_Graph

These graph clearly shows the difference of weight between WMA and EMA. Now lets make a simple program using mindscape.

Now lets calculate the exponential moving average. Here is a simple formula to calculate the EMA.

EMA_Formula

Here EMAn is the EMA for nth day and EMAn-1 is the EMA for previous day and here is the formula to calculate the factor.

EMA_Factor

For the first day, we don’t have any EMA for previous day, so we use SMA then uses EMA for all next calculations. Here are the auxiliary functions to calculate the EMA.

Code Snippet
double Sum(double[] data)
{
    double sum = 0;

    foreach (var d in data)
    {
        sum += d;
    }

    return sum;
}

double Average(double[] data)
{
    if (data.Length == 0)
        return 0;

    return Sum(data) / data.Length;
}

private double CalculateFactor(int days)
{
    if (days < 0)
        return 0;

    return 2.0 / (days + 1);
}

 

Here is a function to calculate exponential moving average (EMA).

Code Snippet
double[] ExponentialMovingAverage(double[] data, int window)
{
    if (data.Length < window)
        return null;

    int diff = data.Length – window;
    double[] newdata = data.Take(window).ToArray();
    double factor = CalculateFactor(window);
    double sma = Average(newdata);

    IList<double> result = new List<double>();
    result.Add(Math.Round(sma, 2));
    emaData.ChartData.Add(Math.Round(sma, 2));

    for (int i = 0; i < diff; i++)
    {
        double prev = result[result.Count – 1];
        double price = data[window + i];
        double next = factor * (price – prev) + prev;
        result.Add(Math.Round(next, 2));
    }
    
    return result.ToArray();
}

 

Here is complete XAML code of the program.

Code Snippet
<Window x:Class="WpfEMA.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
              xmlns:ms="clr-namespace:Mindscape.WpfElements.Charting;assembly=Mindscape.WpfElements"
        Title="Exponential Moving Average" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="5*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
          <ms:Chart Margin="5" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="3"
                  Title="Exponential Moving Average" DataContext="{Binding ChartData}">
            <ms:Chart.XAxis>
                <ms:ChartAxis Title="Time"/>
            </ms:Chart.XAxis>
            <ms:Chart.YAxis>
                <ms:ChartAxis Title="Price"/>
            </ms:Chart.YAxis>
            <ms:LineSeries ItemsSource="{Binding}"
                           SeriesBrush="Green"
                                       YBinding="{Binding}" Title="EMA"/>
        </ms:Chart>
        <TextBlock Grid.Column="0" Grid.Row="1" Margin="10" VerticalAlignment="Center">
            Window Length
        </TextBlock>
        <ComboBox Grid.Column="1" Grid.Row="1" Margin="10" HorizontalContentAlignment="Center"
                  ItemsSource="{Binding WindowLength}"
                  SelectedItem="{Binding SelectedWindowLength}" />
        <Button Grid.Column="2" Grid.Row="1" Margin="10" Click="Button_Click">
            Calculate
        </Button>
    </Grid>
</Window>

 

And here is complete C# code of the program.

Code Snippet
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Windows;

namespace WpfEMA
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private EMA emaData = new EMA();
        IList<double> data = new List<double>();

        public MainWindow()
        {
            InitializeComponent();                        

            data.Add(22.27);
            data.Add(22.19);
            data.Add(22.08);
            data.Add(22.17);
            data.Add(22.18);
            data.Add(22.13);
            data.Add(22.23);
            data.Add(22.43);
            data.Add(22.24);
            data.Add(22.29);
            data.Add(22.15);
            data.Add(22.39);
            data.Add(22.38);
            data.Add(22.61);
            data.Add(23.36);
            data.Add(24.05);
            data.Add(23.75);
            data.Add(23.83);
            data.Add(23.95);
            data.Add(23.63);
            data.Add(23.82);
            data.Add(23.87);

            emaData.WindowLength.Add(8);
            emaData.WindowLength.Add(9);
            emaData.WindowLength.Add(10);
            emaData.WindowLength.Add(11);
            emaData.WindowLength.Add(12);
            
            DataContext = emaData;
        }

        double[] ExponentialMovingAverage(double[] data, int window)
        {
            if (data.Length < window)
                return null;

            int diff = data.Length – window;
            double[] newdata = data.Take(window).ToArray();
            double factor = CalculateFactor(window);
            double sma = Average(newdata);

            IList<double> result = new List<double>();
            result.Add(Math.Round(sma, 2));
            emaData.ChartData.Add(Math.Round(sma, 2));

            for (int i = 0; i < diff; i++)
            {
                double prev = result[result.Count – 1];
                double price = data[window + i];
                double next = factor * (price – prev) + prev;
                result.Add(Math.Round(next, 2));
            }
            
            return result.ToArray();
        }

        double Sum(double[] data)
        {
            double sum = 0;

            foreach (var d in data)
            {
                sum += d;
            }

            return sum;
        }

        double Average(double[] data)
        {
            if (data.Length == 0)
                return 0;

            return Sum(data) / data.Length;
        }

        private double CalculateFactor(int days)
        {
            if (days < 0)
                return 0;

            return 2.0 / (days + 1);
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            emaData.ChartData.Clear();

            double[] ema = ExponentialMovingAverage(data.ToArray(), emaData.SelectedWindowLength);

            foreach (var d in ema)
            {
                emaData.ChartData.Add(d);
            }
        }
    }    

    public class EMA : INotifyPropertyChanged
    {
        private ObservableCollection<int> _windowLength;
        private ObservableCollection<double> _chartData;
        private int _selectedWindowLength;

        public EMA()
        {
            _windowLength = new ObservableCollection<int>();
            _chartData = new ObservableCollection<double>();

            SelectedWindowLength = 9;
        }

        public ObservableCollection<double> ChartData
        {
            get
            {
                return _chartData;
            }
            
            set
            {
                _chartData = value;
                RaisePropertyChanged("ChartData");
            }
        }

        public ObservableCollection<int> WindowLength
        {
            get
            {
                return _windowLength;
            }
            set
            {
                _windowLength = value;
                RaisePropertyChanged("WindowLength");
            }
        }

        public int SelectedWindowLength
        {
            get
            {
                return _selectedWindowLength;
            }
            set
            {
                _selectedWindowLength = value;
                RaisePropertyChanged("SelectedWindowLength");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }    

    }
}

 

Here is the output of the program.

EMA_Output

Posted by: Zeeshan Amjad | June 5, 2013

Creating Bollinger Band using Mindscape


Technical Analysis is an interesting sub field in finance, where we study the price patterns for forecasting purpose. It is also known as charting, because in this field with the help of charting we try to understand the price pattern. One interesting chart we are going to create now is Bollinger Band, introduced by John Bollinger and also trademarked by him.

Calculation of Bollinger band is very simple. It contains three parts, the simple moving average, upper band and lower band.

We can calculate the moving average of for any period, usually it is 20, but any suitable value can be uses.

The upper band is the sum of moving average and k times standard deviation and lower band is the moving average minus k times standard deviation.

If we represent simple moving average by SMA then the upper and lower band can be represent by these formulae.

Upper band = SMA + k * σ

Lower band = SMA – k * σ

Usually the value of k is 2, but any suitable value can be obtained.

Now the first step is to get the price data and perform these calculation. Here we are going to use the same technique we used while creating the overlay chart here.

After that we are going to create some auxiliary methods for our calculation.

Code Snippet
private double CalculateAverage(double[] data)
{
    int count = data.Length;
    double sum = 0;

    for (int i = 0; i < count; i++)
    {
        sum += data[i];
    }

    return sum / count;
}

private double CalculateVariance(double[] data)
{
    int count = data.Length;
    double sum = 0;
    double avg = CalculateAverage(data);

    for (int i = 0; i < count; i++)
    {
        sum += (data[i] – avg) * (data[i] – avg);
    }

    return sum / (count – 1);
}

private double CalculateSTDV(double[] data)
{
    double var = CalculateVariance(data);

    return Math.Sqrt(var);
}

 

We already created a class to store the data points of the chart.

Code Snippet
public class ChartData
{
    public double UpperBandData
    { get; set; }

    public double LowerBandData
    { get; set; }

    public double SMA
    { get; set; }
}

 

We have one class to not only store the chart data, but also get the input from the user interface and perform calculation accordingly. Here is a part of that class.

Code Snippet
public class BollingerBandData : INotifyPropertyChanged
{
    private ObservableCollection<int> _lowerBand;
    private ObservableCollection<int> _upperBand;
    private ObservableCollection<int> _movingAvg;
    private ObservableCollection<int> _length;
    private ObservableCollection<ChartData> _chartData;
    private int _selectedLowerBand;
    private int _selectedUpperBand;
    private int _selectedMovingAvg;
    private int _selectedLength;

    // other stuff
}

 

One we have all the basic stuff then calculating the data point is very easy. Here is a main calculation for the chart data.

Code Snippet
graphdata.ChartData.Clear();

int datalength = graphdata.SelectedMovingAverage + graphdata.SelectedLength;

for (int i = graphdata.SelectedLength – 1; i >= 0; i–)
{
    List<double> price = new List<double>();

    for (int j = 0; j < graphdata.SelectedMovingAverage; j++)
    {
        price.Add(data[i + j].Close);
    }

    double sma = CalculateAverage(price.ToArray());
    double sigma = CalculateSTDV(price.ToArray());
    double lower = sma – (graphdata.SelectedLowerBand * sigma);
    double upper = sma + (graphdata.SelectedUpperBand * sigma);

    graphdata.ChartData.Add(new ChartData() { SMA = sma, LowerBandData = lower, UpperBandData = upper });

 

In user interface, we give the user to select not only the value of upper and lower band constant, but also the period of moving average and how many total points we are going to consider. Here is complete XAML for our program.

Code Snippet
<Window x:Class="WpfBollingerBands.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
              xmlns:ms="clr-namespace:Mindscape.WpfElements.Charting;assembly=Mindscape.WpfElements"
        Title="Bollinger Bands" Height="400" Width="600">
    <Grid DataContext="{Binding}">
        <Grid.RowDefinitions>
            <RowDefinition Height="5*"/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
          <ms:Chart Margin="5" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="5"
                  Title="Bollinger Bands Microsoft Stock" DataContext="{Binding ChartData}">
            <ms:Chart.XAxis>
                <ms:ChartAxis Title="Time"/>
            </ms:Chart.XAxis>
            <ms:Chart.YAxis>
                <ms:ChartAxis Title="Price"/>
            </ms:Chart.YAxis>
            <ms:LineSeries ItemsSource="{Binding}"
                           SeriesBrush="Green"
                           YBinding="{Binding LowerBandData}" Title="Lower Band"/>
            <ms:LineSeries ItemsSource="{Binding}"
                           SeriesBrush="Blue"
                           YBinding="{Binding SMA}" Title="Moving Average"/>
            <ms:LineSeries ItemsSource="{Binding}"
                           SeriesBrush="Green"
                                       YBinding="{Binding UpperBandData}" Title="Upper Band"/>
        </ms:Chart>
        <TextBlock Grid.Column="0" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
            Upper band
        </TextBlock>
        <TextBlock Grid.Column="1" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
            Lower band
        </TextBlock>
        <TextBlock Grid.Column="2" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
            Moving Avg Window
        </TextBlock>
        <TextBlock Grid.Column="3" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center">
            Length
        </TextBlock>
        <ComboBox Margin="10" Grid.Column="0" Grid.Row="2" SelectedItem="{Binding SelectedUpperBand}"
                  ItemsSource="{Binding UpperBand}"/>
        <ComboBox Margin="10" Grid.Column="1" Grid.Row="2" SelectedItem="{Binding SelectedLowerBand}"
                  ItemsSource="{Binding UpperBand}"/>
        <ComboBox Margin="10" Grid.Column="2" Grid.Row="2" SelectedItem="{Binding SelectedMovingAverage}"
                  ItemsSource="{Binding MovingAverageWindow}"/>
        <ComboBox Margin="10" Grid.Column="3" Grid.Row="2" SelectedItem="{Binding SelectedLength}"
                          ItemsSource="{Binding Length}"/>
        <Button Margin="10" Grid.Column="4" Grid.Row="2" Click="Button_Click">Calculate</Button>
    </Grid>
</Window>

 

And here is complete C# code of the program.

Code Snippet
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace WpfBollingerBands
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private BollingerBandData graphdata = new BollingerBandData();
        private List<TickerData> data = new List<TickerData>();

        public MainWindow()
        {
            InitializeComponent();

            string filename = @"C:\zamjad\Data\MSFT.csv";

            data = (from line in File.ReadAllLines(filename)
                        let tickerData = line.Split(',')
                        select new TickerData()
                        {
                            Date = Convert.ToDateTime(tickerData[0]),
                            Open = Convert.ToDouble(tickerData[1]),
                            High = Convert.ToDouble(tickerData[2]),
                            Low = Convert.ToDouble(tickerData[3]),
                            Close = Convert.ToDouble(tickerData[4]),
                            Volume = Convert.ToInt32(tickerData[5]),
                            AdjClose = Convert.ToDouble(tickerData[6])
                        }).ToList();

            graphdata.LowerBand.Add(1);
            graphdata.LowerBand.Add(2);
            graphdata.LowerBand.Add(3);
            graphdata.LowerBand.Add(1);

            graphdata.UpperBand.Add(1);
            graphdata.UpperBand.Add(2);
            graphdata.UpperBand.Add(3);
            graphdata.UpperBand.Add(4);

            graphdata.MovingAverageWindow.Add(10);
            graphdata.MovingAverageWindow.Add(20);
            graphdata.MovingAverageWindow.Add(40);
            graphdata.MovingAverageWindow.Add(50);

            graphdata.Length.Add(10);
            graphdata.Length.Add(30);
            graphdata.Length.Add(50);
            graphdata.Length.Add(100);

            DataContext = graphdata;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            graphdata.ChartData.Clear();

            int datalength = graphdata.SelectedMovingAverage + graphdata.SelectedLength;

            for (int i = graphdata.SelectedLength – 1; i >= 0; i–)
            {
                List<double> price = new List<double>();

                for (int j = 0; j < graphdata.SelectedMovingAverage; j++)
                {
                    price.Add(data[i + j].Close);
                }

                double sma = CalculateAverage(price.ToArray());
                double sigma = CalculateSTDV(price.ToArray());
                double lower = sma – (graphdata.SelectedLowerBand * sigma);
                double upper = sma + (graphdata.SelectedUpperBand * sigma);

                graphdata.ChartData.Add(new ChartData() { SMA = sma, LowerBandData = lower, UpperBandData = upper });
            }
        }

        private double CalculateAverage(double[] data)
        {
            int count = data.Length;
            double sum = 0;

            for (int i = 0; i < count; i++)
            {
                sum += data[i];
            }

            return sum / count;
        }

        private double CalculateVariance(double[] data)
        {
            int count = data.Length;
            double sum = 0;
            double avg = CalculateAverage(data);

            for (int i = 0; i < count; i++)
            {
                sum += (data[i] – avg) * (data[i] – avg);
            }

            return sum / (count – 1);
        }

        private double CalculateSTDV(double[] data)
        {
            double var = CalculateVariance(data);

            return Math.Sqrt(var);
        }
    }

    public class ChartData
    {
        public double UpperBandData
        { get; set; }

        public double LowerBandData
        { get; set; }

        public double SMA
        { get; set; }
    }

    public class BollingerBandData : INotifyPropertyChanged
    {
        private ObservableCollection<int> _lowerBand;
        private ObservableCollection<int> _upperBand;
        private ObservableCollection<int> _movingAvg;
        private ObservableCollection<int> _length;
        private ObservableCollection<ChartData> _chartData;
        private int _selectedLowerBand;
        private int _selectedUpperBand;
        private int _selectedMovingAvg;
        private int _selectedLength;

        public BollingerBandData()
        {
            _lowerBand = new ObservableCollection<int>();
            _upperBand = new ObservableCollection<int>();
            _movingAvg = new ObservableCollection<int>();
            _length = new ObservableCollection<int>();
            _chartData = new ObservableCollection<ChartData>();

            SelectedLowerBand = 2;
            SelectedUpperBand = 2;
            SelectedMovingAverage = 20;
            SelectedLength = 30;
        }

        public ObservableCollection<ChartData> ChartData
        {
            get
            {
                return _chartData;
            }
            set
            {
                _chartData = value;
                RaisePropertyChanged("ChartData");
            }
        }

        public ObservableCollection<int> LowerBand
        {
            get
            {
                return _lowerBand;
            }
            set
            {
                _lowerBand = value;
                RaisePropertyChanged("LowerBand");
            }
        }
        
        public ObservableCollection<int> UpperBand
        {
            get
            {
                return _upperBand;
            }
            set
            {
                _upperBand = value;
                RaisePropertyChanged("UpperBand");
            }
        }

        public ObservableCollection<int> MovingAverageWindow
        {
            get
            {
                return _movingAvg;
            }
            set
            {
                _movingAvg = value;
                RaisePropertyChanged("MovingAverageWindow");
            }
        }
        
        public ObservableCollection<int> Length
        {
            get
            {
                return _length;
            }
            set
            {
                _length = value;
                RaisePropertyChanged("Length");
            }
        }
        public int SelectedLowerBand
        {
            get
            {
                return _selectedLowerBand;
            }
            set
            {
                _selectedLowerBand = value;
                RaisePropertyChanged("SelectedLowerBand");
            }
        }

        public int SelectedUpperBand
        {
            get
            {
                return _selectedUpperBand;
            }
            set
            {
                _selectedUpperBand = value;
                RaisePropertyChanged("SelectedUpperBand");
            }
        }

        public int SelectedMovingAverage
        {
            get
            {
                return _selectedMovingAvg;
            }
            set
            {
                _selectedMovingAvg = value;
                RaisePropertyChanged("SelectedMovingAverage");
            }
        }

        public int SelectedLength
        {
            get
            {
                return _selectedLength;
            }
            set
            {
                _selectedLength = value;
                RaisePropertyChanged("SelectedLength");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void RaisePropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    public class TickerData
    {
        public DateTime Date
        { get; set; }

        public double Open
        { get; set; }

        public double High
        { get; set; }

        public double Low
        { get; set; }

        public double Close
        { get; set; }

        public int Volume
        { get; set; }

        public double AdjClose
        { get; set; }
    }
}

 

The default length is set to 30, but here is the output of the program with length of 100.

BollingerBand

Posted by: Zeeshan Amjad | May 26, 2013

Overlay chart using Mindscape


Sometimes we need to display more than one chart at a time on top of each other to get more information on it. It is specially true in finance where we are displaying lots of chats together to get a better idea about market. In fact there is a separate field in finance for this names “Technical Analysis”. We will study this in more detail in coming post, but as a first step we need to study the overlay chart and see how can we display the overlay chart.

In fact displaying more than one chart using mindscape is nothing different than displaying only one type of chart. Here we are taking an example of display the moving average and closing price of the Microsoft stock price. Our first step is to get the historical price of Microsoft. There are different ways of this, but we tried http://finance.yahoo.com. We downloaded the Microsoft historical price by typing this at internet browser.

http://ichart.finance.yahoo.com/table.csv?s=MSFT

 

This price download in one CVS file and we can easily read this CVS file using LINQ. We just removed the header of the CVS file to make my LINQ query simple. Our first step is to create a simple class to store this information.

Code Snippet
public class TickerData
{
    public DateTime Date
    { get; set; }

    public double Open
    { get; set; }

    public double High
    { get; set; }

    public double Low
    { get; set; }

    public double Close
    { get; set; }

    public int Volume
    { get; set; }

    public double AdjClose
    { get; set; }
}

 

Here is a LINQ query to read the CVS file.

Code Snippet
var data = (from line in File.ReadAllLines(filename)
            let tickerData = line.Split(',')
            select new TickerData()
            {
                Date = Convert.ToDateTime(tickerData[0]),
                Open = Convert.ToDouble(tickerData[1]),
                High = Convert.ToDouble(tickerData[2]),
                Low = Convert.ToDouble(tickerData[3]),
                Close = Convert.ToDouble(tickerData[4]),
                Volume = Convert.ToInt32(tickerData[5]),
                AdjClose = Convert.ToDouble(tickerData[6])
            }).ToList();

 

Now comes to the chart portion of it. In Mindscape we simply uses the different chart type one after another. In this example we are going to display a Line Series and Bar Series together.

Here is complete XAML of our program.

Code Snippet
<Window x:Class="WpfOverlayChart.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
              xmlns:ms="clr-namespace:Mindscape.WpfElements.Charting;assembly=Mindscape.WpfElements"
        Title="Overlay Chart" Height="400" Width="600">
    <Grid>
        <ms:Chart Margin="5" Title="Overlay Chart of Microsoft Price">
            <ms:Chart.XAxis>
                <ms:ChartAxis Title="Time" MajorTickSpacing="1"/>
            </ms:Chart.XAxis>
            <ms:Chart.YAxis>
                <ms:ChartAxis Title="Price" MajorTickSpacing="1" Minimum="30"/>
            </ms:Chart.YAxis>
            <ms:BarSeries ItemsSource="{Binding}"
                          YBinding="{Binding Price}" Title="Closing price">
                <ms:BarSeries.SeriesBrush>
                    <LinearGradientBrush>
                        <GradientStop Color="AliceBlue" Offset="0"/>
                        <GradientStop Color="Blue" Offset="0.5"/>
                        <GradientStop Color="AliceBlue" Offset="1"/>
                    </LinearGradientBrush>
                </ms:BarSeries.SeriesBrush>
            </ms:BarSeries>
            <ms:LineSeries ItemsSource="{Binding}"
                           SeriesBrush="Green"
                           YBinding="{Binding Price}" Title="Moving Average"/>
        </ms:Chart>
    </Grid>
</Window>

 

And here is complete C# code of our program.

Code Snippet
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Windows;

namespace WpfOverlayChart
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<ChartData> chartData = new ObservableCollection<ChartData>();

        public MainWindow()
        {
            InitializeComponent();

            string filename = @"C:\zamjad\Data\MSFT.csv";

            var data = (from line in File.ReadAllLines(filename)
                        let tickerData = line.Split(',')
                        select new TickerData()
                        {
                            Date = Convert.ToDateTime(tickerData[0]),
                            Open = Convert.ToDouble(tickerData[1]),
                            High = Convert.ToDouble(tickerData[2]),
                            Low = Convert.ToDouble(tickerData[3]),
                            Close = Convert.ToDouble(tickerData[4]),
                            Volume = Convert.ToInt32(tickerData[5]),
                            AdjClose = Convert.ToDouble(tickerData[6])
                        }).ToList();
            
            int count = chartData.Count;

            for (int i = 0; i < 30; i++)
            {
                double sum = 0.0;

                for (int j = 0; j < 10; j++)
                {
                    sum += data[i + j].Close;
                }

                double sma = sum / 10;

                chartData.Add(new ChartData() { Price = data[i].Close, SMA = sma });
            }

            DataContext = chartData;
            
        }
    }

    public class ChartData
    {
        public double SMA
        { get; set; }

        public double Price
        { get; set; }
    }

    public class TickerData
    {
        public DateTime Date
        { get; set; }

        public double Open
        { get; set; }

        public double High
        { get; set; }

        public double Low
        { get; set; }

        public double Close
        { get; set; }

        public int Volume
        { get; set; }

        public double AdjClose
        { get; set; }
    }
}

 

This is an output of our program.

OverlayChart

Posted by: Zeeshan Amjad | May 15, 2013

ListBox in ComboBox


I came across a request to insert listbox inside the combobox. This particular task is quite simple and we already saw an example reverse of it here where we display combobox inside the listbox. The basic idea is same that is created an ObservableCollection of ObservableCollection and then set the ItemsSource property accordingly.

The second part of the question is little tricky. The second part of the question is to display the selected item of inner listbox in the combobox. We already solved similar problem where we have different presentation in combo box and selected item by using ItemContinerStyle property here. In that example we display multiple column in combo box but display only one data when we select the data. Now we are going to use the same technique here.

But here the problem is how can we get the selected item of listbox so we can display it in combo box.

Here we create an additional property in the class to store the selected item of the list box.

Code Snippet
public class State
{
    public string SelectedCity
    { get; set; }

    public ObservableCollection<string> Cities
    { get; set; }
}

 

We can get the selected item value by using SelectedItem property of listbox using data binding.

Code Snippet
<ListBox HorizontalContentAlignment="Stretch"
         SelectedItem="{Binding Path=SelectedCity}"
         ItemsSource="{Binding Cities}"/>

 

Rest is quite easy, we just display the selected city in the combo box.

Here is a complete C# code of the program.

Code Snippet
using System.Collections.ObjectModel;
using System.Windows;

namespace WpfComboList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<State> States = new ObservableCollection<State>();

        public MainWindow()
        {
            InitializeComponent();

            ObservableCollection<string> maryland = new ObservableCollection<string>();

            maryland.Add("Frederick");
            maryland.Add("German Town");
            maryland.Add("Baltimore");
            maryland.Add("Annapolis");

            ObservableCollection<string> texas = new ObservableCollection<string>();

            texas.Add("Houston");
            texas.Add("Dallas");
            texas.Add("San Antonio");

            ObservableCollection<string> california = new ObservableCollection<string>();

            california.Add("Los Angeles");
            california.Add("Fremont");

            States.Add(new State() { Cities = maryland });
            States.Add(new State() { Cities = texas });
            States.Add(new State() { Cities = california });

            DataContext = States;
        }
    }
    
    public class State
    {
        public string SelectedCity
        { get; set; }

        public ObservableCollection<string> Cities
        { get; set; }
    }
}

 

And here is Complete XAML code of the program.

Code Snippet
<Window x:Class="WpfComboList.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        Title="List In Combo" Height="350" Width="525">
    <Grid>
        <ComboBox HorizontalContentAlignment="Stretch" Height="35" Margin="5" ItemsSource="{Binding}">
            <ComboBox.ItemContainerStyle>
                <Style TargetType="{x:Type ComboBoxItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Border Margin="1" BorderBrush="Brown">
                                    <ListBox HorizontalContentAlignment="Stretch"
                                             SelectedItem="{Binding Path=SelectedCity}"
                                             ItemsSource="{Binding Cities}"/>
                                </Border>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ComboBox.ItemContainerStyle>
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock VerticalAlignment="Center" Text="{Binding Path=SelectedCity}"/>
                </DataTemplate>
            </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</Window>

Here is an output of the program when we open the Combo box.

ListInCombo_1

And here is an output when we select something from the listbox.

ListInCombo_2

« Newer Posts - Older Posts »

Categories