【问题标题】:How to add colors to a combobox in metro app?如何在 Metro 应用程序中为组合框添加颜色?
【发布时间】:2012-04-07 18:49:44
【问题描述】:

我想使用 C# 将颜色列表添加到 Metro 应用程序中的组合框。反过来,用户可以从列表中选择一种特定的颜色来改变背景。

可能的可用库是 Windows.UI.Colors

这里是一个简单的桌面应用程序的链接:http://www.c-sharpcorner.com/uploadfile/mahesh/how-to-load-all-colors-in-a-combobox-using-C-Sharp/

但我无法将其移植到 Metro 环境。

此外,颜色名称以及颜色本身作为列表项将是一个巨大的优势。

来自 MSDN 的另一个线程: http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/880a3b5b-e287-4cdc-a1ab-d1cd4a19aedb/

【问题讨论】:

  • 您将代码移植到 Metro 的程度如何?
  • RowlandShaw:一点也不。正如我所提到的,图书馆不同,所以无能为力。此外,GetProperties() 也不可用。另外,XAML 中有 但我不知道它的用法。

标签: c# windows-8 microsoft-metro


【解决方案1】:

此代码适用于我:

var colorsTypeInfo = typeof(Colors).GetTypeInfo();
var properties = colorsTypeInfo.DeclaredProperties;
Dictionary<string, string> colours = new Dictionary<string, string>();
foreach (var dp in properties)
{
    colours.Add(dp.Name, dp.GetValue(typeof(Colors)).ToString());
}

请确保您已添加以下参考,否则将无法正常工作

using System.Reflection;
using Windows.UI;

【讨论】:

    【解决方案2】:
    <ComboBox x:Name="cbColorNames" Grid.Row="1" Height="40"
          ItemsSource="{Binding Colors}"
          SelectedItem="{Binding SelectedColorName, Mode=TwoWay}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Grid Background="Black">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Rectangle Width="35" Height="20" Fill="{Binding Name}" Margin="5,0"/>
                <TextBlock Grid.Column="1" Margin="10,0,0,0" Text="{Binding Name}" Foreground="White"/>
            </Grid>
        </DataTemplate>
    </ComboBox.ItemTemplate>
    

    这是 xaml 文件。

    private static void LoadColors()
    {
        var t = typeof(Colors);
        var ti = t.GetTypeInfo();
        var dp = ti.DeclaredProperties;
        colors = new List<PropertyInfo>();
        foreach (var item in dp)
        {
            colors.Add(item);
        }
    }
    private static List<PropertyInfo> colors;
    public List<PropertyInfo> Colors
    {
        get
        {
            if (colors == null)
                LoadColors();
            return colors;
        }
    }
    

    这是 C# 代码。

    感谢大家的支持和帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多