의존속성, 의존프로퍼티
(DEPENDENCY PROPERTY)
www.topcredu.co.kr 이종철
•
•
•
•
<Window x:Class="DependencyPropertyTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="295" Width="300">
<Window.ContextMenu>
<ContextMenu MenuItem.Click="ContextMenu_Click">
<MenuItem Header="Red"/>
<MenuItem Header="Green"/>
<MenuItem Header="Blue"/>
<MenuItem Header="Orange"/>
</ContextMenu>
</Window.ContextMenu>
<TextBox x:Name="textBox1" Height="23" TextWrapping="Wrap"
Text="TextBox" Width="120"/> </Window>
MainWindow.xaml
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)));
MainWindow.xaml.cs
private static void
OnMyPropertyChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
MainWindow win = d as MainWindow;
SolidColorBrush brush =
(SolidColorBrush)new
BrushConverter().ConvertFromString(e.NewValue.T
oString());
win.Background = brush;
win.Title = (e.OldValue == null) ?
"제목없음" : e.OldValue.ToString();
win.textBox1.Text = e.NewValue.ToString();
}
private void
ContextMenu_Click(object sender,
RoutedEventArgs e)
{
string str = (e.Source as
MenuItem).Header as string;
MyText = str;
}
}
}
실행화면
 의존 속성은 의존속성을 선언, 등록, 프로퍼티 생성 세단계로 작성된다.
 의존 속성 선언 및 등록
//의존 속성 선언 및 등록
public static readonly DependencyProperty MyProperty =
DependencyProperty.Register(
" MyText", //등록할 의존 속성 이름
typeof(String),
typeof(MainWindow),
new FrameworkPropertyMetadata(new
PropertyChangedCallback(OnMyPropertyChanged))); //속성변경시 호출될 메
소드
 의 존 속 성 은 읽 기 전 용 (readonly) 필 드 로 선 언 되 는 데 이 것 은 오 직
FrameworkElement 클래스의 static 생성자에서만 설정될 수 있다는 것을 의미
한다.
 DependencyProperty 클래스에는 public 생성자가 없기 때문에 static 메소드인
DencyProperty.Register()를 사용해서 등록한다.
 Register 메서드의 입력 파라미터의 첫 번째 파라미터는 프로퍼티 이름이다. 여
기서는 “MyText”, 두 번째 인자는 프로퍼티(MyText)가 사용할 데이터 타입으로
여기에서는 String 이다. 세 번째 인자는 프로퍼티를 소유하게 될 타입, 이 예제
에서는 MainWindow 클래스가 된다. 네 번째 인자는 실제로 어떻게 동작할 것
인지에 대한 옵션을 설정을 할당해 준다. FrameworkPropertyMetadata 객체를
통하여 만약 값이 수정되었을 때의 알림을 어떻 받을 것인가를 정의했으며 본
예제에서는 OnMyPropertyChanged 메소드가 알림을 받을 콜백 함수로 정의되
었다. 선택적으로 new ValidataValueCallback을 사용하여 값의 유효성 검사를 어
떻게 할 것인지 등을 설정하면 된다. 네 번째, 다섯 번째 파라미터는 옵션 파라미
터이다.
 DependencyProperty(MyProperty)를 위한 래퍼 프로퍼티 MyText 선언
public String MyText
{
get { return (String)GetValue(MyProperty); }
set { SetValue(MyProperty, value); }
}
이 래퍼 프로퍼티에서는 System.Windows.DependencyObject 클래스의
GetValue()와 SetValue() 메서드를 이용해서 get, set을 정의해야 한다.
 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로부터 상속받은 속성으로 모두 의존
속성이다.

(WPF학원/WPF교육)C#, WPF, XAML의 의존속성, 의존프로퍼티에 대해 알아봅니다.

  • 1.
  • 2.
  • 3.
  • 4.
    <Window x:Class="DependencyPropertyTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" Height="295"Width="300"> <Window.ContextMenu> <ContextMenu MenuItem.Click="ContextMenu_Click"> <MenuItem Header="Red"/> <MenuItem Header="Green"/> <MenuItem Header="Blue"/> <MenuItem Header="Orange"/> </ContextMenu> </Window.ContextMenu> <TextBox x:Name="textBox1" Height="23" TextWrapping="Wrap" Text="TextBox" Width="120"/> </Window> MainWindow.xaml
  • 5.
    MainWindow.xaml.cs using System; using System.Windows; usingSystem.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)));
  • 6.
    MainWindow.xaml.cs private static void OnMyPropertyChanged(DependencyObjectd, DependencyPropertyChangedEventArgs e) { MainWindow win = d as MainWindow; SolidColorBrush brush = (SolidColorBrush)new BrushConverter().ConvertFromString(e.NewValue.T oString()); win.Background = brush; win.Title = (e.OldValue == null) ? "제목없음" : e.OldValue.ToString(); win.textBox1.Text = e.NewValue.ToString(); } private void ContextMenu_Click(object sender, RoutedEventArgs e) { string str = (e.Source as MenuItem).Header as string; MyText = str; } } }
  • 7.
  • 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 MenuClick 이벤트에서는 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로부터 상속받은 속성으로 모두 의존 속성이다.