'Dependency Property'에 해당되는 글 1건

  1. 2010.09.30 [wp7] UserControl에 간략하게 Dependency Property 쓰는법
Windows Phone 72010. 9. 30. 17:52

먼저 UserControl을 이용하여 Dependecy Property를 쓴 간략한 예제를 먼저 보자

<UserControl x:Class="WorldHoliday.Views.HolidayText"
 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 
    mc:Ignorable="d"
 
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
 
    FontSize="{StaticResource PhoneFontSizeNormal}"
 
    Foreground="{StaticResource PhoneForegroundBrush}"
 
    x:Name="RootText"
 
    >    
 
    <StackPanel>
 
        <TextBlock Text="{Binding Path=HolidayTextValue,ElementName=RootText}" VerticalAlignment="Center"/>
 
        <Path Data="M0,52 L480.02109,52" Fill="#FFF4F4F5" Height="1" Margin="0,0,-1.021,7" Stretch="Fill" Stroke="White" UseLayoutRounding="False" VerticalAlignment="Bottom"/>
 
    </StackPanel>
 
</UserControl>
 
 

 

그냥 usercontrol에 Textbox 하나 넣은 것이다. 이미 구현된 완성본을 넣었다. 일단 완성 해 놓고 시작을 했다.

 

자 이제 behind코드를 보자.

public partial class HolidayText : UserControl
 
   {
 
       public string HolidayTextValue
 
       {
 
           get { return (string)GetValue(HolidayTextValueProperty); }
 
           set { SetValue(HolidayTextValueProperty, value); }
 
       }
 
 
       public static readonly DependencyProperty HolidayTextValueProperty =
 
          DependencyProperty.Register("HolidayTextValue", typeof(string), typeof(HolidayText), new PropertyMetadata(string.Empty));
 
 
 
 
       public HolidayText()
 
       {
 
           InitializeComponent();            
 
       }
 
   }

 

그냥 간단하게 넣은것이다.

 

약간 설명을 하자면

Name = 등록할 속성의 이름

Propeprty=  속성의 타입

ownerType = 속성을 포함한 부모의 타입

typeMetaData = 속성 메타데이타 지정 (보통 callback 함수를 지정함)

 

마지막은 null로 지정가능하고 필요에 따라서 call back 함수를 만들어서 사용할수도 있다. 자세한 설명은

 

http://drum-83.tistory.com/82

 

여기를 참조 하자

 

자 이제 이 유저컨트롤을 사용한 코드를 보자

 

HolidayText ht = new HolidayText()
 
{
 
    HolidayTextValue = day
 
}; 
 
 
HolidayMonthList.Children.Add(ht);

 

자 이제 이 간단한 코드를 자세히 살펴보자..

 

이건 HolidayText라는 유저 컨트롤에 HolidayTextValue라는 Dependency Property를 정의 하고 그냥 string형 값을

 

주면 usercontrol안의 TextBlock에 내용을 뿌려주는 것이다.

 

중요한 건 저렇게 Dependency Property를 주는데 꼭 ElementName을 줘야 한다는 것이다 중요!!!!

 

<TextBlock Text="{Binding Path=HolidayTextValue,ElementName=RootText}" VerticalAlignment="Center"/>

 

이부분에서 ElementName은 위에 UserControl에 x:Name="RootText" 이렇게 정의 하였다…

 

만약 ElementName을 주지 않는다면 바인딩이 제대로 되지 않으므로 주의 하자

 

참고 : http://decav.com/blogs/andre/archive/2007/05/27/wpf-binding-to-properties-in-your-usercontrol-or-window.aspx <—elementName의 중요성

Posted by 동동(이재동)