1

我正在使用Expression Blend 4在Silverlight 4中的UserControl中創建一個觸摸滾動列表。我已經在我的UserControl中創建了依賴項屬性,我想像ListBox一樣工作。 ItemSource是我想要在列表中顯示的對象列表,datatemplate是它應該顯示的方式。在UserControl中實現DataTemplate DependencyProperty

我如何處理我的UserControl中的這些屬性?我有一個StackPanel,其中應添加所有數據模板,顯示數據c。

如何在通過ItemSource循環來將它們添加到列表(StackPanel)時將我的IEnumerable中的數據應用於DataTemplate。

 public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(InertiaScrollBox), null); 
    public IEnumerable ItemsSource 
    { 
     get{ return (IEnumerable)GetValue(ItemsSourceProperty); } 
     set{ SetValue(ItemsSourceProperty, value); } 
    } 

    public static readonly DependencyProperty ItemTemplateProperty = DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(InertiaScrollBox), null); 
    public DataTemplate ItemTemplate 
    { 
     get { return (DataTemplate)GetValue(ItemTemplateProperty); } 
     set { SetValue(ItemTemplateProperty, value); } 
    } 

這有點難以解釋,但希望你明白,否則請問。在此先感謝

+0

好像你可能會更好要麼繼承了列表框或使用行爲。通常,依賴項屬性用於控件而不是用戶控件。 – Bryant

+0

使用控件模板或繼承現有控件可能會更好,但我們不知道所有的細節,並且問題與數據模板有關。 – vorrtex

+0

我正在創建一個觸摸慣性滾動列表。 Subclassing ListBox讓我很難捕獲所有的鼠標事件,因爲ListBox中的ListBoxItem控件會捕獲默認的鼠標左鍵。也許它可以完成,但我認爲它會比我現在得到的更復雜,它運行得很漂亮:) – brianfroelund

回答

1

如果不處理它們的更改,則依賴項屬性將毫無用處。 首先,您應該添加PropertyChanged回調。在我的示例中,我將它們添加到內聯中,並調用UpdateItems私有方法。

public static readonly DependencyProperty ItemsSourceProperty = 
DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(InertiaScrollBox), 
    new PropertyMetadata((s, e) => ((InertiaScrollBox)s).UpdateItems())); 

public static readonly DependencyProperty ItemTemplateProperty = 
DependencyProperty.Register("ItemTemplate", typeof(DataTemplate), typeof(InertiaScrollBox), 
    new PropertyMetadata((s, e) => ((InertiaScrollBox)s).UpdateItems())); 

然後你就可以調用DataTemplate類的LoadContent方法,並從ItemsSource作爲DataContext的設置項目到返回的視覺元素:

private void UpdateItems() 
{ 
    //Actually it is possible to use only the ItemsSource property, 
    //but I would rather wait until both properties are set 
    if(this.ItemsSource == null || this.ItemTemplate == null) 
     return; 

    foreach (var item in this.ItemsSource) 
    { 
     var visualItem = this.ItemTemplate.LoadContent() as FrameworkElement; 
     if(visualItem != null) 
     { 
      visualItem.DataContext = item; 
      //Add the visualItem object to a list or StackPanel 
      //... 
     } 
    } 
} 
+0

我其實昨天已經知道了,但沒有時間填寫答案。這非常接近我的做法。這實際上有點簡單,因爲我有單獨的處理程序,在我的情況下是不必要的。非常感謝! – brianfroelund

相關問題