February 18, 2014

TaskbarItemInfo in MVVM and Sample WPF Converter Usage

In this case we are using a WPF TaskbarItemInfo to show progress on an icon in the Taskbar. The taskbar progress value takes a double value between 0.0d and 1.0d. However, in this cae the progresss value is generated as an integer percentage between 0 and 100. So we create a converter class to convert our interger value between 0 and 100 to the double value. An alternative would be to create another property that creates the progress value in the appropriate form.
// Convert an integer percentage (0 to 100) to a double 
// between (0.0d and 1.0d)
public class IntPercentageToDoubleConverter : IValueConverter
{
    public object Convert(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        double res = 0.0d;
        if (value is int)
        {
            int intVal = (int)value;
            res = intVal / 100.0d;
            if (res < 0.0d)
                res = 0.0d;
            else if (res > 100.0d)
                res = 100.0d;
        }
        return res;            
    }

    public object ConvertBack(object value, Type targetType,
        object parameter, CultureInfo culture)
    {
        return null;
    }
}
In the Xaml we first need to create an instance of the converter. A few namespace declarations are required:
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PhotoBackupApp.ViewModel"
Create the converter instance:
<Window.Resources>
    <local:IntPercentageToDoubleConverter x:Key="intPercentageToDoubleConverter" />
</Window.Resources>
Use the converter with the bound proprety
<Window.TaskbarItemInfo>
    <TaskbarItemInfo ProgressValue="{Binding Mode=OneWay, 
       Path=ProgressPercentage, 
       Converter={StaticResource intPercentageToDoubleConverter},
       UpdateSourceTrigger=PropertyChanged}" 
       ProgressState="Normal" />
</Window.TaskbarItemInfo>
The 2 important declarartions here are 'Path=ProgressPercentage, Converter={StaticResource intPercentageToDoubleConverter},'. This is the property to bind to and the converter instance to use.

No comments: