2011-03-31 59 views
2

我在通過父級UserControl上的數據綁定使用DependencyProperty設置自定義用戶控件的屬性時遇到問題。使用DependencyProperty訪問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上)。

我沒有在調試輸出窗口中收到任何運行時綁定錯誤。我只是不能設置實體屬性的值。有任何想法嗎?

回答

3

您正試圖在c-tor中使用Entity屬性,這太快了。 C-tor將在物業價值將被給予之前被解僱。

什麼ü需要做的是一個PropertyChanged事件處理程序添加到的DependencyProperty,像這樣:

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 2011-03-31 19:46:26

相關問題