PageRenderTime 26ms CodeModel.GetById 15ms app.highlight 6ms RepoModel.GetById 1ms app.codeStats 1ms

/V2.2/trunk/Quickstarts/Commanding/Desktop/Commanding.OrderModule/Converter/StringToNullableNumberConverter.cs

#
C# | 57 lines | 35 code | 6 blank | 16 comment | 8 complexity | 761ec7def1a6db69e0563d2a5838773f MD5 | raw file
 1//===================================================================================
 2// Microsoft patterns & practices
 3// Composite Application Guidance for Windows Presentation Foundation and Silverlight
 4//===================================================================================
 5// Copyright (c) Microsoft Corporation.  All rights reserved.
 6// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY
 7// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT
 8// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
 9// FITNESS FOR A PARTICULAR PURPOSE.
10//===================================================================================
11// The example companies, organizations, products, domain names,
12// e-mail addresses, logos, people, places, and events depicted
13// herein are fictitious.  No association with any real company,
14// organization, product, domain name, email address, logo, person,
15// places, or events is intended or should be inferred.
16//===================================================================================
17using System;
18using System.Globalization;
19using System.Windows.Data;
20
21namespace Commanding.Modules.Order.Converter
22{
23    public class StringToNullableNumberConverter : IValueConverter
24    {
25        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
26        {
27            return value;
28        }
29
30        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
31        {
32            string stringValue = value as string;
33            if (stringValue != null)
34            {
35                if (targetType == typeof(int?))
36                {
37                    int result;
38                    if (int.TryParse(stringValue, out result))
39                        return result;
40                    
41                    return null;
42                }
43
44                if (targetType == typeof(decimal?))
45                {
46                    decimal result;
47                    if (decimal.TryParse(stringValue, out result))
48                        return result;
49
50                    return null;
51                }
52            }
53
54            return value;
55        }
56    }
57}