我想将所有Windows.UI.Colors绑定到XAML页面中的ListBox(ListView?),通用Windows应用程序(适用于Windows 10,Visual Studio 2015中)。
I found以这种方式获取所有系统颜色:
Dictionary<string, Windows.UI.Color> Colors()
{
var _Colors = typeof(Windows.UI.Colors)
// using System.Reflection;
.GetRuntimeProperties()
.Select(c => new
{
Color = (Windows.UI.Color)c.GetValue(null),
Name = c.Name
});
return _Colors.ToDictionary(x => x.Name, x => x.Color);
}
我不知道如何将它绑定到ListBox
<ListBox ItemsSource="{x:Bind colors}" >
</ListBox>
理想情况下,列表项文本应为颜色名称,列表项目背景为颜色值。
答案 0 :(得分:4)
@ Romasz回答的另一种方法:
将Color()
方法更改为属性,并返回包含SolidColorBrush
值而不是Color
的词典,如下所示:
public Dictionary<string, SolidColorBrush> Colors
{
get
{
var _Colors = typeof(Windows.UI.Colors)
// using System.Reflection;
.GetRuntimeProperties()
.Select(c => new
{
Color = new SolidColorBrush((Windows.UI.Color)c.GetValue(null)),
Name = c.Name
});
return _Colors.ToDictionary(x => x.Name, x => x.Color);
}
}
然后,在XAML中,将列表框更改为:
<ListBox ItemsSource="{x:Bind Colors}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Background="{Binding Value}">
<TextBlock Text="{Binding Key}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 1 :(得分:1)
关于绑定,你需要改进几件事(我建议你再读一些at MSDN)。至于你的代码 - 在xaml中,你需要声明 ItemTemplate 的外观,并绑定到 DataContext 中的属性。您还需要一个转换器将 Color 转换为 Brush :
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView ItemsSource="{Binding MyColors}">
<ListView.Resources>
<local:ColorToBrush x:Key="ColorToBrush"/>
</ListView.Resources>
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Color, Converter={StaticResource ColorToBrush}}">
<TextBlock Text="{Binding Name}"/>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
后面的代码 - 转换器类,适当的属性以及在构造函数中设置 DataContext :
public class ColorToBrush : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language) => new SolidColorBrush((Windows.UI.Color)value);
public object ConvertBack(object value, Type targetType, object parameter, string language) { throw new NotImplementedException(); }
}
public sealed partial class MainPage : Page
{
// this is the shortcut of {get { return ... }}
public Array MyColors => typeof(Windows.UI.Colors).GetRuntimeProperties()
.Select(c => new
{
Color = (Windows.UI.Color)c.GetValue(null),
Name = c.Name
}).ToArray();
public MainPage()
{
this.InitializeComponent();
DataContext = this;
}
}
当然您也可以绑定到 Dictionary ,然后您必须在XAML绑定中进行交换:Name -> Key
和Color -> Value
。