简体   繁体   English

如何在数据绑定中为itemscontrol设置生成的项目?

[英]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. 如果我使用ListBox进行数据绑定,则listbox会为每个项目生成一个listboxitem,组合框和comboBoxItem也是如此。 My question is - how do i set it myself for a given ItemsControl? 我的问题是-如何为给定的ItemsControl自行设置? (eg make the containing element be Border)? (例如,使包含元素为Border)?

The default item used to wrap each item is a ContentPresenter 用于包装每个项目的默认项目是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. 我不确定您为什么要覆盖它,因为它没有视觉外观或会干扰您的UI的特定行为。

You can set the ItemTemplate if you want to wrap each item in a Border object 如果要将每个项目都包装在Border对象中,则可以设置ItemTemplate

<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 如果要对ContentPresenter应用任何特定样式,请设置ItemContainerStyle

<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 - 用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. 这是ListBox所做的工作-在我的控件中,我也应该覆盖它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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