WPF 중요 개념중에 하나인 Dependency Object에 대해서 xaml, cs 중심으로 알아 보겠습니다.
1. Declare DependencyObject Class
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
namespace SteveDependencyProperties.DependencyProperties
{
/// <summary>
/// Inheritance DependencyObject Class
/// </summary>
public class MyTestDependencyObject : DependencyObject
{
/// <summary>
/// Regist Dependency Object
/// </summary>
public static readonly DependencyProperty
MyTestDependencyProperty = DependencyProperty.Register(
"MyTestDependency",
typeof(string),
typeof(MyTestDependencyObject),
new PropertyMetadata("Test Dependency", OnMyTestDependencyPropertyChange));
//new PropertyMetadata(3515, OnMyTestDependencyPropertyChange));
/// <summary>
/// MyTestDependency get/set property
/// </summary>
public string MyTestDependency
{
get
{
Debug.WriteLine("MyTestDependency GetValue");
return (string)GetValue(MyTestDependencyProperty);
}
set
{
Debug.WriteLine("MyTestDependency SetValue");
SetValue(MyTestDependencyProperty, value);
}
}
/// <summary>
/// xaml binding value change receive event
/// </summary>
/// <param name="d"></param>
/// <param name="e"></param>
private static void OnMyTestDependencyPropertyChange(DependencyObject d,DependencyPropertyChangedEventArgs e)
{
Debug.WriteLine("Property changed: {0}", e.NewValue);
}
}
}
2. Using XAML
<Window x:Class="SteveDependencyProperties.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:localDependency="clr-namespace:SteveDependencyProperties.DependencyProperties" <-(1)
Title="MainWindow" Height="350" Width="525">
<Grid>
<WrapPanel>
<TextBlock>MyTestDependency</TextBlock>
<TextBox Text="{Binding Path=MyTestDependency, <-(2)
Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
<TextBox.DataContext>
<localDependency:MyTestDependencyObject/> <-(3)
</TextBox.DataContext>
</TextBox>
<TextBox Text=" and "></TextBox>
</WrapPanel>
</Grid>
</Window>
3. 정리
위 xaml에서 처럼 사용을 하면 된다.
(1) 사용을 원하는 XAML 상단에 Dependency Object를 선언한다.
(2) 1.에서 선언한 클래스에 있는 DependencyObjcet 여기서는 MyTestDependency를 바인딩(Binding)한다.
(3) Binding한 오브젝트에 대해서 DataContext를 연동한다.
출처: 다년간의 프로그래밍 경험
'C#(CSharp) > WPF' 카테고리의 다른 글
ObservableCollection 바인딩(Binding) (0) | 2015.04.08 |
---|---|
결합 속성(?) Attached Property (0) | 2015.04.08 |
사용자 정의 이벤트 만들기 (0) | 2015.04.08 |
XAML Custom Namespace (0) | 2015.04.08 |
다국어 작업(Globalization, Localization) (0) | 2015.04.02 |