Windows Phone 72011. 12. 7. 14:10

Custom UserControl을 만들고 안에 TextBox를 하나 넣었다고 가정하자

여기 TextBox에 Text를 바꾸기 위해서는 어떻게 하는게 좋을까?

Behind에서 그냥 강제로 바꾸는것이 좋을까? 아니다 그거보다 쉬운방법이 있다.

바로 DataContext에 넣어서 바인딩 하는 방법이다.

일단 유저컨트롤을 만들고 상위 Grid의 이름을 정하자 기본적으로 "LayoutRoot" 로 지정되어 있을것이다.

그리고 비하인드에서 의존 프로퍼티를 하나 만들자. 이름은 그냥 ItemSource로 지었다

#region ItemSource

       /// <summary>
       /// Gets or sets the ItemSource possible Value of the TransferTrnInfoModel object.
       /// </summary>
       public TrnInfoModel ItemSource
       {
           get { return (TrnInfoModel)GetValue(ItemSourceProperty); }
           set { SetValue(ItemSourceProperty, value); }
       }

       /// <summary>
       /// Identifies the ItemSource dependency property.
       /// </summary>
       public static readonly DependencyProperty ItemSourceProperty =
                   DependencyProperty.Register(
                         "ItemSource",
                         typeof(TrnInfoModel),
                         typeof(GeneralTrainInfoControl),
                         new PropertyMetadata(OnItemSourcePropertyChanged));

       /// <summary>
       /// ItemSourceProperty property changed handler.
       /// </summary>
       /// <param name="d">TrainInfoControl that changed its ItemSource.</param>
       /// <param name="e">DependencyPropertyChangedEventArgs.</param>
       private static void OnItemSourcePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
       {
           GeneralTrainInfoControl _TrainInfoControl = d as GeneralTrainInfoControl;
           if (_TrainInfoControl != null)
           {
               _TrainInfoControl.SetItemSource((TrnInfoModel)e.NewValue);
           }
       }

       #endregion ItemSource

       private void SetItemSource(TrnInfoModel param)
       {
           LayoutRoot.DataContext = param;
       }

그리고 source를 받으면

LayoutRoot.DataContext = param;

이렇게 dataContext에 넣게 바꿨다.

TrnInfoModel은 모델 클래스이고

<ct:GeneralTrainInfoControl ItemSource="{Binding GeneralTrainInfoSource}">

이런식으로 사용 하면 된다.

물론 모델 클래스에는 값이 다 정의 해서 넘겨줘야 한다.

이렇게 하면 해당 UserControl에서 Text같은곳에 바인딩만 걸어주면 끝~

구지 textbox.Text = TrnInfoModel.name

이런식으로 일일히 하지 않아도 되는것이다.

그리고 그냥 usrcontrol만들고 그안에 text만 binding할려면 젤 쉬운방법은

위처럼 궂이 Itemsource 의존 프로퍼티를 만들지 않고

그냥 DataContext에 넣으면 된다.

Posted by 동동(이재동)