简体   繁体   中英

WPF - create a grid of colors

I have a ViewModel in WPF that looks something like this:

public class SwatchViewModel
{
    public ObservableCollection<Color> Colors { get; private set; }
}

I want to display each of the colors in the collection, laying them out in columns. Each of the columns should take up the same amount of space in the control and all columns combined should fill the width of the control. The control can be sized arbitrarily.

So if Colors contained { Colors.Red, Colors.Green, Colors.Blue } then I would want three columns, each taking up a third of the width of the control, with each column colored appropriately.

What is the best way of doing this? It seems suited for an ItemsControl except for the fact an ItemsControl doesn't stretch its items to fill the available width... that's a job for the Grid ... but grid's columns can't be bound....

XAML is preferred, though I'm quite happy to fall back to C# if necessary.

You can use a UniformGrid . A uniform grid suits your needs exactly, it adds cells according to the number of children it contains.

Example:

<ItemsControl ItemsSource="..." ItemTemplate="...">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

Setting Rows to 1 constrains the row count to 1 (duh...).

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