简体   繁体   中英

WPF ListBoxItem does not stretch to the maximum width in wrappanel

I am trying to make a Listbox that it contains custom control and it could wrap automic.My listbox xaml code like below.I need to three items in each row and stretch to maximum width.It will be wrap to next row if items more than three. I need my custom control stretch on in Horizontal not both all side. How can I do that?

<ScrollViewer HorizontalScrollBarVisibility="Disabled">
            <ListBox>
                <ListBox.Template>
                    <ControlTemplate TargetType="{x:Type ListBox}">
                        <WrapPanel Orientation="Horizontal" IsItemsHost="True" />
                    </ControlTemplate>
                </ListBox.Template>

                <ListBoxItem>
                    <controls:TransducerItem  Margin="5,10"/>
                </ListBoxItem>

                <ListBoxItem>
                    <controls:TransducerItem  Margin="5,10"/>
                </ListBoxItem>


                <ListBoxItem>
                    <controls:TransducerItem  Margin="5,10"/>
                </ListBoxItem>

                <ListBoxItem>
                    <controls:TransducerItem Margin="5,10" />
                </ListBoxItem>

                <ListBoxItem>
                    <controls:TransducerItem  Width="200" Margin="5,10" />
                </ListBoxItem>
            </ListBox>

Use a UniformGrid with three columns as ItemsPanel :

<ListBox>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="3" VerticalAlignment="Top"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    ...
</ListBox>

You might also use your TransducerItem control in the ItemTemplate of the ListBox

<ListBox.ItemTemplate>
    <DataTemplate>
        <controls:TransducerItem  Margin="5,10"/>  
    </DataTemplate>
</ListBox.ItemTemplate>

and then bind the ListBox's ItemsSource property to a collection of data items that hold each TransducerItem's data:

<ListBox ItemsSource="{Binding TranducerData}">
    ...
</ListBox>

Take a look at the Data Templating Overview article on MSDN.

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