5. MainWindow.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace DependencyPropertyTest {
public partial class MainWindow : Window
{
public MainWindow() {
InitializeComponent();
}
public String MyText {
get { return
(String)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
public static readonly
DependencyProperty MyProperty
= DependencyProperty.Register(
" MyText",
typeof(String),
typeof(MainWindow),
new
FrameworkPropertyMetadata(new
PropertyChangedCallback(OnMyPr
opertyChanged)));
8. 의존 속성은 의존속성을 선언, 등록, 프로퍼티 생성 세단계로 작성된다.
의존 속성 선언 및 등록
//의존 속성 선언 및 등록
public static readonly DependencyProperty MyProperty =
DependencyProperty.Register(
" MyText", //등록할 의존 속성 이름
typeof(String),
typeof(MainWindow),
new FrameworkPropertyMetadata(new
PropertyChangedCallback(OnMyPropertyChanged))); //속성변경시 호출될 메
소드
9. 의 존 속 성 은 읽 기 전 용 (readonly) 필 드 로 선 언 되 는 데 이 것 은 오 직
FrameworkElement 클래스의 static 생성자에서만 설정될 수 있다는 것을 의미
한다.
DependencyProperty 클래스에는 public 생성자가 없기 때문에 static 메소드인
DencyProperty.Register()를 사용해서 등록한다.
Register 메서드의 입력 파라미터의 첫 번째 파라미터는 프로퍼티 이름이다. 여
기서는 “MyText”, 두 번째 인자는 프로퍼티(MyText)가 사용할 데이터 타입으로
여기에서는 String 이다. 세 번째 인자는 프로퍼티를 소유하게 될 타입, 이 예제
에서는 MainWindow 클래스가 된다. 네 번째 인자는 실제로 어떻게 동작할 것
인지에 대한 옵션을 설정을 할당해 준다. FrameworkPropertyMetadata 객체를
통하여 만약 값이 수정되었을 때의 알림을 어떻 받을 것인가를 정의했으며 본
예제에서는 OnMyPropertyChanged 메소드가 알림을 받을 콜백 함수로 정의되
었다. 선택적으로 new ValidataValueCallback을 사용하여 값의 유효성 검사를 어
떻게 할 것인지 등을 설정하면 된다. 네 번째, 다섯 번째 파라미터는 옵션 파라미
터이다.
10. DependencyProperty(MyProperty)를 위한 래퍼 프로퍼티 MyText 선언
public String MyText
{
get { return (String)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
이 래퍼 프로퍼티에서는 System.Windows.DependencyObject 클래스의
GetValue()와 SetValue() 메서드를 이용해서 get, set을 정의해야 한다.
11. Context Menu Click 이벤트에서는 MyText 프로퍼티에 값을 설정하면 자동으로
위에서 선언한 콜백 함수(OnMyPropertyChanged)가 호출된다.
private void ContextMenu_Click(object sender, RoutedEventArgs e)
{
string str = (e.Source as MenuItem).Header as string;
MyText = str;
}
우리가 흔히 알고 있는 Height와 Width와 같은 멤버들은 FrameworkElement를
상속받았고 Content 속성은 ControlContent로부터 상속받은 속성으로 모두 의존
속성이다.