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

相关问题