不写代码在WPF里实现枚举预置颜色

这篇博客展示了如何通过C#的反射机制获取`System.Windows.Media.Colors`枚举中的所有颜色,并在WPF界面中以颜色块和名称的形式进行展示。代码演示了在XAML中绑定和呈现颜色属性,创建了一个色彩丰富的颜色列表布局。

知道颜色的命名很重要,再烂的程序也需要美化,用反射,了解系统里有什么颜色可用,不写代码其实是喙头,原理就是这样

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>

效果图

 

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值