Very simple color picker made of combobox

走远了吗. 提交于 2019-12-24 03:06:08

问题


This is my xaml:

<ComboBox Name="comboColors">
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" />
                            <TextBlock Text="{Binding Name}" />
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

And here is a population of combobox items in c#:

comboColors.ItemsSource = typeof(Colors).GetProperties();

Now the question is - how to make this combo show its items in drop-down list 4-5-6 or more columns?

And another question - how could I insert a title for this drop down? Say "palett colors are:" This is a text field - not a pair of color- name perhaps I could add transparent color + title as first element but how to make it be i a first row?

May be a datagrid as dropdown is a cool idea? I ll try it now)


回答1:


In your .xaml

<ComboBox Name="comboColors">
    <ComboBox.ItemsPanel>
        <ItemsPanelTemplate>
            <Grid Loaded="table_Loaded" />
        </ItemsPanelTemplate>
    </ComboBox.ItemsPanel>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0 2 5 2" />
                <TextBlock Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

And in your .xaml.cs

...
private static readonly int COLUMS = 5;
...
comboColors.ItemsSource = typeof(Colors).GetProperties();
...

private void table_Loaded(object sender, RoutedEventArgs e) {
    Grid grid = sender as Grid;
    if (grid != null) {
        if (grid.RowDefinitions.Count == 0) {
            for (int r = 0; r <= comboColors.Items.Count / COLUMS; r++) {
                grid.RowDefinitions.Add(new RowDefinition());
            }
        }
        if (grid.ColumnDefinitions.Count == 0) {
            for (int c = 0; c < Math.Min(comboColors.Items.Count, COLUMS); c++) {
                grid.ColumnDefinitions.Add(new ColumnDefinition());
            }
        }
        for (int i = 0; i < grid.Children.Count; i++) {
            Grid.SetColumn(grid.Children[i], i % COLUMS);
            Grid.SetRow(grid.Children[i], i / COLUMS);
        }
    }
}


来源:https://stackoverflow.com/questions/30440634/very-simple-color-picker-made-of-combobox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!