简体   繁体   English

WPF - 创建颜色网格

[英]WPF - create a grid of colors

I have a ViewModel in WPF that looks something like this: 我在WPF中有一个看起来像这样的ViewModel:

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. 因此,如果Colors包含{ Colors.Red, Colors.Green, Colors.Blue }那么我会想要三列,每列占据控件宽度的三分之一,每列都适当地着色。

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.... 它似乎适合ItemsControl除了ItemsControl没有拉伸它的项目来填充可用的宽度......这是Grid的一个工作......但网格的列不能绑定....

XAML is preferred, though I'm quite happy to fall back to C# if necessary. XAML是首选,但我很乐意在必要时回退到C#。

You can use a UniformGrid . 你可以使用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...). Rows设置为1会将行计数限制为1(duh ...)。

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

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