0

현재 TagItem이라는 UserControl 클래스를 만들었습니다.이 클래스는 현재 mainButton이라는 하나의 Button으로만 구성되어 있습니다.종속성 속성이있는 UserControl

이 태그에는 DisplayedTag라는 종속성 속성이 있습니다.이 속성은 Tag 유형 (내 태그에 대한 데이터가 들어있는 간단한 클래스)입니다. 내 목표는 사용자가 XAML에서 DisplayedTag를 설정할 때 mainButton의 텍스트를 Tag의 TagName으로 업데이트해야한다는 것입니다.

TagItem의 코드 :

public Tag DisplayedTag 
    { 
     get { return (Tag)GetValue(DisplayedTagProperty); } 
     set 
     { 
      SetValue(DisplayedTagProperty, value); 
     } 
    } 

    // Using a DependencyProperty as the backing store for MyProperty. 
    // This enables animation, styling, binding, etc... 
    public static DependencyProperty DisplayedTagProperty = 
     DependencyProperty.Register("DisplayedTag", 
      typeof(Tag), 
      typeof(TagItem), 
      new PropertyMetadata(new Tag(), 
       OnDisplayedTagPropertyChanged)); 


    private static void OnDisplayedTagPropertyChanged(DependencyObject source, 
     DependencyPropertyChangedEventArgs e) 
    { 
     // Put some update logic here... 

     Tag tag = (Tag)e.NewValue; 
     mainButton.Content = tag.TagName; 

    } 

XAML에서 :

<local:TagItem DisplayedTag="{Binding}"/> 

mainButton가 아닌 동안 OnDisplayedTagPropertyChanged은 정적이기 때문에이 작동하지 않습니다. 나는 여기서 완전히 잘못된 길을 걷고 있을지 모르며, 단순한 문제를 푸는 것에 대한 방향을 정말로 고맙게 생각할 것입니다.

답변

2

OnDisplayedTagPropertyChanged 콜백의 source 매개 변수에는 UserControl 파생 컨트롤이 있습니다. mainButton에 액세스 할 수 있도록 캐스트해야합니다.

나는 (모든 것이 정확한지 모르겠다) 클래스에 대한 어떤 이름을했다 :

private static void OnDisplayedTagPropertyChanged(DependencyObject source, 
    DependencyPropertyChangedEventArgs e) 
{ 
    MyUserControl ctrl = source as MyUserControl; 
    if(ctrl == null) // should not happen 
     return; 

    Button b = ctrl.mainButton; 

    Tag tag = (Tag)e.NewValue; 
    mainButton.Content = tag.TagName; 

} 
+0

좋아, 내가 조금을 시도 ... – Fratyx

관련 문제