Frage

I am trying to create a dynamic table in WPF based off an ItemsControl. Ideally I want each element of the collection rendered with a specific style and to fit 3 across the table before it wraps and goes to the next row. It works NEARLY perfectly, the only problem is I have a width of about 30 pixels empty space after entry 3 in the list. If you add up the numbers you will see that the textblocks + margin are equal to 140 each, so 3 of those is 420 - the table width is 450, so there is the problem you would think.

Sadly not.

If I increase the first text block to width of 110 instead of 105, just a small change, which would give a total width for 3 entries of 435, still less than 450 - which is the width of the table, then it wraps after only 2 entries and leaves a large empty space on the right.

My suspicion is that it might be due to "reserved space" that WPF holds for a vertical scrollbar, as that is usually 20 wide, which would give my usable space as 430, and 435 is higher than that, so it wraps.

My question is, how can I hide all scrollbars and make them not display at all or hold any reserved space, so that I can use the full width of the items control?

XAML below

<ItemsControl ItemsSource="{Binding TradeCategories}" Grid.Row="1">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" MaxWidth="450"  Background="{StaticResource SubTableRow}"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal" MaxWidth="150">
                <TextBlock Width="105" FontSize="10" Text="{Binding CategoryName}" Foreground="{StaticResource SubTableText}" Margin="5,0,0,0"/>
                <TextBlock Width="25" FontSize="10" Text="{Binding CategoryCount}" TextAlignment="Center" Background="{StaticResource SubTableHighlightCell}" Foreground="{StaticResource SubTableText}" />
            </StackPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
War es hilfreich?

Lösung

It looks like the width of the ItemControl is smaller than you expect, it may be restricted by it's container.

An easy fix is to replace

<WrapPanel Orientation="Horizontal" MaxWidth="450" ...

by

<WrapPanel Orientation="Horizontal" MinWidth="450" ...

So as to be sure that the WrapPanel has enough room for 3 items. That way, even if the ItemControl is smaller than 450, you'll still have 3 items per row.

Another solution is to force the Width of the ItemControl to be 450.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top