■ IValueConverter 인터페이스 : 실수↔십진수 값 변환자 만들기

----------------------------------------------------------------------------------------------------

DoubleToDecimalValueConveter.cs

using System;
using System.Globalization;
using System.Windows.Data;

/// <summary>
///
배정도 실수↔십진수 값 변환자
/// </summary>
[ValueConversion(typeof(double), typeof(decimal))]
public class DoubleToDecimalValueConverter : IValueConverter
{
   
//////////////////////////////////////////////////////////////////////////////////////////////////// Method
   ////////////////////////////////////////////////////////////////////////////////////////// Public

   #region 변환하기 - Convert(sourceValue, targetType, parameter, cultureInfo)

   
/// <summary>
   
/// 변환하기
   /// </summary>
   /// <param name="sourceValue"></param>
   /// <param name="targetType">타겟 타입</param>
   /// <param name="parameter">파라미터</param>
   /// <param name="cultureInfo">CultureInfo</param>
   /// <returns>변환 값</returns>
   public object Convert(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo)
   {
       
decimal targetValue = new Decimal((double)sourceValue);

       
if(parameter != null)
       {
           targetValue =
Decimal.Round(targetValue, Int32.Parse(parameter as string));
       }

       
return targetValue;
   }

   #endregion

   #region
역변환하기 - ConvertBack(sourceValue, targetType, parameter, cultureInfo)

   
/// <summary>
   /// 역변환하기
   /// </summary>
   /// <param name="sourceValue">소스 값</param>
   /// <param name="targetType">타겟 타입</param>
   /// <param name="parameter">파라미터</param>
   /// <param name="cultureInfo">CultureInfo</param>
   /// <returns>역변환 값</returns>
   public object ConvertBack(object sourceValue, Type targetType, object parameter, CultureInfo cultureInfo)
   {
       
return Decimal.ToDouble((decimal)sourceValue);
   }

   #endregion
}

TestWindow.xaml

<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:src="clr-namespace:TestProject"
   Title="십진수 스크롤바">
   <Window.Resources>
       <src:DoubleToDecimalValueConverter x:Key="DoubleToDecimalValueConverterKey" />
   </Window.Resources>
   <StackPanel>
       <ScrollBar
           Name="scrollBar"
           Margin="24"
           Orientation="Horizontal"
           Maximum="100"
           SmallChange="1"
           LargeChange="10" />
       <Label
           HorizontalAlignment="Center"
           Content="{Binding ElementName=scrollBar, Path=Value, Converter={StaticResource DoubleToDecimalValueConverterKey}, ConverterParameter=2}" />
   </StackPanel>
</
Window>
----------------------------------------------------------------------------------------------------

Posted by 사용자 icodebroker
TAG