2011-03-31 4 views
2

부모 UserControl에서 데이터 바인딩을 통해 DependencyProperty를 사용하여 사용자 지정 사용자 정의 컨트롤의 속성을 설정하는 데 문제가 있습니다. 여기 DependencyProperty가있는 UserControl 코드의 바운드 개체에 액세스

내 사용자 지정 UserControl에 코드입니다 :

public partial class UserEntityControl : UserControl 
{ 
    public static readonly DependencyProperty EntityProperty = DependencyProperty.Register("Entity", 
     typeof(Entity), typeof(UserEntityControl)); 

    public Entity Entity 
    { 
     get 
     { 
      return (Entity)GetValue(EntityProperty); 
     } 
     set 
     { 
      SetValue(EntityProperty, value); 
     } 
    } 

    public UserEntityControl() 
    { 
     InitializeComponent(); 
     PopulateWithEntities(this.Entity); 
    } 
} 

즉 동적 엔티티에 저장된 값을 기준으로 사용자 정의 컨트롤을 구축 할 것입니다 때문에 내가 뒤에있는 코드에서 엔티티 속성에 액세스 할 수 있습니다. 내가 겪고있는 문제는 Entity 속성이 설정되지 않는다는 것입니다.

<ListBox Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding SearchResults}"  x:Name="SearchResults_List"> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <!--<views:SearchResult></views:SearchResult>--> 
      <eb:UserEntityControl Entity="{Binding}" ></eb:UserEntityControl> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

내가 엔티티의 관찰 가능한 컬렉션 (법인과 동일한 유형 인의 SearchResult에 목록 상자의 ItemsSource를 설정하고 다음은

내가 부모 사용자 컨트롤에 바인딩을 설정하고 어떻게 사용자 지정 UserControl).

디버그 출력 창에 런타임 바인딩 오류가 발생하지 않습니다. Entity 속성의 값을 설정할 수 없습니다. 어떤 아이디어?

답변

3

너무 빨리 입력자에서 엔터티를 사용하려고합니다. 속성 값이 주어지기 전에 ctor가 해고 될 것입니다. 유해야 할 일은

지금처럼하는 DependencyProperty로하여 PropertyChanged 이벤트 처리기를 추가하는 것입니다

public static readonly DependencyProperty EntityProperty = DependencyProperty.Register("Entity", 
typeof(Entity), typeof(UserEntityControl), new PropertyMetadata(null, EntityPropertyChanged)); 

    static void EntityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
    { 
     var myCustomControl = d as UserEntityControl; 

     var entity = myCustomControl.Entity; // etc... 
    } 

    public Entity Entity 
    { 
     get 
     { 
      return (Entity)GetValue(EntityProperty); 
     } 
     set 
     { 
      SetValue(EntityProperty, value); 
     } 
    } 
+1

붐! 헤드 샷! 이것은 완벽하게 작동했습니다. Elad 감사합니다! – njebert

관련 문제