简体   繁体   中英

Binding a UserControl to a ListBox ItemSource

I have an ObservableCollection that has a list of objects.

I would like to bind this observable collection to the ListBox but not in a way that each object gets shown inside the ListView, but instead that Each object creates a UserControl that has the object itself as input parameter.

To give a similar example; imagine a server browser where each line is a UserControl and data is stored in a List/ObservableCollection and then displayed inside a frontend ListBox.

I have this XAML code in my MainWindow.xaml

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

And this is the style that invokes the UserControl

<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>

and in the MainWindow.xaml.cs I have:

ObservableCollection<Bill> Bills {get;set;}

And inside the constructor I just added few objects.

I would like that the Bill object gets pushed to the User Control in this manner:

UserControl BillItem (Bill BindedObject)
{ ... }

But I don't know how to do that.

If I understood correctly, you need something like this:

<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 needs to have dependency property, because you cant pass to constructor:

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));

on the view have an item that inherits from ItemsControl eg listbox, then place your objects in an ObservableCollection property in your VM. then simply bind to that property in the ItemsControl/listbox or whatevers ItemsSource property

ItemSource="{Binding MyObjectCollection}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM