不写代码在WPF里实现枚举预置颜色
作者:互联网
知道颜色的命名很重要,再烂的程序也需要美化,用反射,了解系统里有什么颜色可用,不写代码其实是喙头,原理就是这样
type colorType=typeof(Colors);
PropertyInfo[] colorProperties=colorType.GetProperties();
把上面的代码写在xaml里就成了。
<Window x:Class="EnumColors.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:EnumColors"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="EnumColors" Height="450" Width="800" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ObjectDataProvider x:Key="ColorType" ObjectType="{x:Type sys:Type}" MethodName="GetType">
<ObjectDataProvider.MethodParameters>
<sys:String>System.Windows.Media.Colors,PresentationCore</sys:String>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
<ObjectDataProvider x:Key="ColorProperties" ObjectInstance="{StaticResource ColorType}" MethodName="GetProperties"/>
</Window.Resources>
<Grid>
<ListBox Margin="5" ItemsSource="{Binding Source={StaticResource ColorProperties}}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<Rectangle Margin="5,5,5,1" Width="100" Height="50" Fill="{Binding Name}"/>
<TextBlock HorizontalAlignment="Center" Text="{Binding Name}" Grid.Row="1"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="5"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
</Grid>
</Window>
效果图
标签:预置,颜色,不写,代码,Colors,WPF,colorType 来源: https://blog.csdn.net/fdc2017/article/details/113835968