2016-06-10 79 views
0

我有一个ObservableCollection对象列表。将用户控件绑定到列表框项目源

我想将此可观察集合绑定到ListBox,但不是以每个对象都显示在ListView内的方式,而是每个对象都创建一个UserControl,该对象本身作为输入参数。

给出一个类似的例子;设想一个服务器浏览器,其中每行是UserControl,数据存储在List/ObservableCollection中,然后显示在前端ListBox中。

我有这样的XAML代码我MainWindow.xaml

<ListBox HorizontalContentAlignment="Stretch" ItemsSource="{Binding Bills}" ItemContainerStyle="{StaticResource BillStyle}"> 
</ListBox> 

这是调用用户控件

<Style TargetType="{x:Type ListBoxItem}" x:Key="BillStyle"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type ListBoxItem}"> 
       <ns:BillItem /> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

和我有MainWindow.xaml.cs风格:

ObservableCollection<Bill> Bills {get;set;} 

而在构造函数中,我只是添加了几个对象。

我想该法案对象被推到了用户控制以这种方式:

UserControl BillItem (Bill BindedObject) 
{ ... } 

但我不知道该怎么做。

回答

0

在视图上有一个itemControl继承自ItemsControl,例如listbox,然后将您的对象放置在VM的ObservableCollection属性中。然后简单地绑定到ItemsControl中/列表框或凡是ItemsSource属性,物业

的ItemSource = “{结合MyObjectCollection}”

+0

如何为ItemSource中的每个对象创建一个UserControl? – DethoRhyne

+0

我改变了我的问题,你可以检查一下吗? – DethoRhyne

+0

我不确定我明白你为什么要为每个项目设置一个用户控件。我是否会正确地假设你想为你的集合中的每个项目添加一个列表框来显示它的项目?如果是这样,你会更好地使用列表框来显示所有的项目,然后第二个列表框,在第一个列表框中显示所选项目的子项目。 – LiamHarries

1

如果我理解正确的,你需要的东西是这样的:

<ItemsControl ItemsSource="{Binding Path=ListOfObjects}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <StackPanel Orientation="Vertical" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <local:MyUserControl MyProperty="{Binding}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

的MyUserControl需要有依赖属性,因为你不能传递给构造函数:

public object MyProperty 
{ 
    get { return (object)GetValue(MyPropertyProperty); } 
    set { SetValue(MyPropertyProperty, value); } 
} 

public static readonly DependencyProperty MyPropertyProperty = 
    DependencyProperty.Register("MyProperty", typeof(object), typeof(MyUserControl), new PropertyMetadata(false)); 
+0

我从来没想过这个!感谢您的想法!但是,在执行时出现以下错误。 '在'System.Windows.StaticResourceExtension'上提供值引发了一个异常。'在ListBox行 – DethoRhyne

+0

我已经修复了鞋面,但是现在我得到了'Billing_Components的类型初始值设定器。BillItem'抛出一个异常。'如果我使用'PropertyMetadata(false)',并且我没有将对象引用设置为对象的一个​​实例。如果U不使用'PropertyMetadata(false)' – DethoRhyne

+0

当我在PropertyMetadata中添加新的BillItem()时,我得到一个空对象。 – DethoRhyne

相关问题