■ Binding 태그 확장의 ElementName 속성을 사용해 특정 엘리먼트 속성을 바인딩하는 방법을 보여준다.
▶ DoubleToDecimalValueConveter.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
using System; using System.Globalization; using System.Windows.Data; namespace TestProject { /// <summary> /// 실수↔10진수 값 변환자 /// </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, int.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 } } |
▶ MainWindow.xaml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<Window x:Class="TestProject.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:TestProject" Width="800" Height="600" Title="Binding 태그 확장 : ElementName 속성을 사용해 특정 엘리먼트 속성 바인딩하기" FontFamily="나눔고딕코딩" FontSize="16"> <Window.Resources> <local:DoubleToDecimalValueConverter x:Key="DoubleToDecimalValueConverterKey" /> </Window.Resources> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <ScrollBar Name="scrollBar" HorizontalAlignment="Center" Margin="10" Width="500" Height="20" Orientation="Horizontal" Maximum="100" SmallChange="1" LargeChange="10" /> <Label HorizontalAlignment="Center" Margin="10" Content="{Binding ElementName=scrollBar, Path=Value, Mode=OneWay, UpdateSourceTrigger=PropertyChanged, Converter={StaticResource DoubleToDecimalValueConverterKey}, ConverterParameter=2}" /> </StackPanel> </Window> |