2021년 10월 17일 일요일

WPF, 의존프로퍼티(DependencyProperty), 의존속성


원본 : http://ojc.asia/bbs/board.php?bo_table=WPF&wr_id=140&page=2


WPF, 의존프로퍼티(DependencyProperty), 의존속성

 

n  기존의 닷넷 Property에 WPF 요소를 가미하여 새롭게 탄생.

n  XAML, C# 코드 비하인드에서 사용 가능하며 의존속성 값이 변경되면 자동으로 어떤 것을 로드되게 하거나 랜더링 되도록 할 수 있는데 애니메이션스타일링데이터바인딩 등에 자주 사용된다.

n  어떤 속성을 애니메이션 시켜야 하거나 데이터 바인딩을 하려면 그 속성은 반드시 의존 속성이어야 한다.

n  기본으로 제공되는 UI 컨트롤은 대부분의 속성이 의존 속성으로 되어 있다.

n  FrameworkElement , Control 등과 같이 DependencyObject 에서 파생 된 클래스에서만 정의 할 수 있습니다.

 

n  우선 간단히 예제를 하나 만들어 보자.

n  비주얼 스튜디오 -> WPF 응용프로그램 프로젝트명 : DependencyPropertyTest

n  MainWindow.xaml

 

<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="BLUE"/>

            <MenuItem Header="YELLOW"/>

            <MenuItem Header="GREEN"/>

            <MenuItem Header="BLACK"/>        </ContextMenu>

    </Window.ContextMenu>

    <TextBox x:Name="textBox1" Height="23" TextWrapping="Wrap" Text="TextBox" Width="120"/> </Window>

 

n  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();

        }

 

          //DependencyProperty(MyProperty)를 위한 래퍼속성 MyColor

        // 이 래퍼속성에서는 System.Windows.DependencyObject 클래스의 //GetValue() SetValue() 메서드를 이용해서 get, set을 정의해야 한다.

        public String MyColor

        {

            get { return (String)GetValue(MyProperty); }

            set { SetValue(MyProperty, value);  }

        }

 

        //의존속성(Dependency Property) MyProperty

        // DependencyProperty 클래스에는 public 생성자가 없기 때문에 static //메소드인 DependencyProperty.Register()를 사용해서 등록한다.

         // 수정이 불가능 하도록 의존속성은 읽기전용(readonly) 필드로 //선언되는데 일반 UI컨트롤의 Height, Width 

//대부분의 의존속성은 FrameworkElement에 DependencyProprty

// 정의되어있다.

public static readonly DependencyProperty MyProperty = DependencyProperty.Register(

            "MyColor",            //의존속성으로 등록될 속성

            typeof(String),         //등록할 의존속성 타입

            typeof(MainWindow),  // 의존속성을 소유하게될 OWNER

            new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMyPropertyChanged)));

//속성값 변경시 호출될 메소드

// 프로퍼티 값의 변경에 따른 Callback 메서드 등 새로운 속성을 추가하기 위해 FrameworkPropertyMetadata를 인자 값으로 전달 할수 있다.

 

        private static void OnMyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        {

            MainWindow win = d as MainWindow;

            SolidColorBrush brush = (SolidColorBrush)new BrushConverter().ConvertFromString(e.NewValue.ToString());

            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;

            MyColor = str;

        }

    }

}

 

n  실행화면

1dfca4e343be71c9c0653621e5b036dd_1596983
 

 

n  의존 속성은 의존속성을 선언등록 그리고 프로퍼티를 생성하는 3단계로 작성된다.

n  의존 속성 선언 및 등록

//의존 속성 선언 및 등록

public static readonly DependencyProperty MyProperty = DependencyProperty.Register(

 " MyColor",            //등록할 의존 속성 이름

  typeof(String),

  typeof(MainWindow),

 new FrameworkPropertyMetadata(new PropertyChangedCallback(OnMyPropertyChanged)));  //속성변경시 호출될 메소드

 

대부분의 UI 컨트롤의 의존속성은 읽기전용(readonly) 필드로 선언되는데 이것은 오직 FrameworkElement 클래스의 static 생성자에서만 설정될 수 있다는 것을 의미한다.

 

DependencyProperty 클래스에는 public 생성자가 없기 때문에 static 메소드인 DependencyProperty.Register()를 사용해서 등록한다.

 

Register 메서드의 입력 파라미터의 첫 번째 파라미터는 프로퍼티 이름이다여기서는 “MyColor”, 두 번째 인자는 프로퍼티(MyColor)가 사용할 데이터 타입으로 여기에서는 String 이다세 번째 인자는 프로퍼티를 소유하게 될 타입이 예제에서는 MainWindow 클래스가 된다네 번째 인자는 실제로 어떻게 동작할 것인지에 대한 옵션을 설정을 할당해 준다. FrameworkPropertyMetadata 객체를 통하여 만약 값이 수정되었을 때의 알림을 어떻게 받을 것인가를 정의했으며 본 예제에서는 OnMyPropertyChanged 메소드가 알림을 받을 콜백 함수로 정의되었다선택적으로 new ValidateValueCallback을 사용하여 값의 유효성 검사를 어떻게 할 것인지 등을 설정하면 된다네 번째다섯 번째 파라미터는 옵션 파라미터이다.

 

n  DependencyProperty(MyProperty)를 위한 래퍼 프로퍼티 MyColor 선언

public String MyColor

{

   get { return (String)GetValue(MyProperty); }

   set { SetValue(MyProperty, value);  }

}

 

이 래퍼 프로퍼티에서는 System.Windows.DependencyObject 클래스의 GetValue() SetValue() 메서드를 이용해서 get, set을 정의해야 한다.

 

n  Context Menu Click 이벤트에서는 MyColor 프로퍼티에 값을 설정하면 자동으로 위에서 선언한 콜백 함수(OnMyPropertyChanged)가 호출된다.

private void ContextMenu_Click(object sender, RoutedEventArgs e)

        {

            string str = (e.Source as MenuItem).Header as string;

            MyColor = str;

        }

 

우리가 흔히 알고 있는 Height Width와 같은 멤버들은 FrameworkElement를 상속받았고 Content 속성은 ControlContent로부터 상속받은 속성으로 모두 의존속성이다  

댓글 없음:

댓글 쓰기

(C#교육동영상)C# ADO.NET 실습 ODP.NET/ODAC 설치 오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원

  (C#교육동영상)C# ADO.NET 실습  ODP.NET/ODAC 설치  오라클 함수 호출 실습, C#학원, WPF학원, 닷넷학원, 자바학원 https://www.youtube.com/watch?v=qIPU85yAlzc&list=PLxU-i...