简体   繁体   中英

how to set the generated item for itemscontrol in databinding?

if I'm using a ListBox for data binding, the listbox generates a listboxitem for each item, same goes for combo box and comboBoxItem. My question is - how do i set it myself for a given ItemsControl? (eg make the containing element be Border)?

The default item used to wrap each item is a ContentPresenter

I am not sure why you'd want to overwrite this, since it has no visual appearance or specific behavior that would mess with your UI.

You can set the ItemTemplate if you want to wrap each item in a Border object

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Border BorderBrush="Blue" BorderThickness="2">
            <TextBlock Text="{Binding }" />
        </Border>
    </DataTemplate>
</ItemsControl.ItemTemplate>

Or set the ItemContainerStyle if you want to apply any specific style to the ContentPresenter

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Grid.Column" Value="{Binding ColumnIndex}" />
        <Setter Property="Grid.Row" Value="{Binding RowIndex}" />
    </Style>
</ItemsControl.ItemContainerStyle>

After digging a little with ILSpy -

Apparently The magic is done in

    protected override DependencyObject GetContainerForItemOverride()
    {
        return new ListBoxItem();
    }

This is where ListBox does it - and in my control I should override this as well.

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