PageRenderTime 16ms CodeModel.GetById 12ms app.highlight 2ms RepoModel.GetById 1ms app.codeStats 0ms

/V4/StockTrader RI/Silverlight/StockTraderRI.Infrastructure.Silverlight/Converters/EnumToBooleanConverter.Silverlight.cs

#
C# | 61 lines | 38 code | 7 blank | 16 comment | 9 complexity | c19a0f52b0c10d787da66326778b9cf5 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 StockTraderRI.Infrastructure.Converters
22{
23    public class EnumToBooleanConverter : IValueConverter
24    {
25        #region IValueConverter Members
26
27        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
28        {
29            var stringParameter = parameter as string;
30            if (value == null || string.IsNullOrEmpty(stringParameter))
31            {
32                return false;
33            }
34
35            return string.Equals(value.ToString(), stringParameter, StringComparison.Ordinal);
36        }
37
38        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
39        {
40            var stringParameter = parameter as string;
41            if (value == null || string.IsNullOrEmpty(stringParameter))
42            {
43                return null;
44            }
45
46            object parsedParameter = Enum.Parse(targetType, stringParameter, true);
47            if (parsedParameter == null)
48            {
49                return null;
50            }
51
52            if ((bool)value)
53            {
54                return parsedParameter;
55            }
56
57            return null;
58        }
59        #endregion
60    }
61}