MenuItem绑定到形状类型的枚举,但仅显示最后一个枚举项的形状

如何解决MenuItem绑定到形状类型的枚举,但仅显示最后一个枚举项的形状

一个类由一个枚举和一个转换器组成,该转换器的工作是将枚举值转换为几何。可以在下面看到:

public enum GeometryEnum
{
    Triangle,Rectangle,RoundedRectangle,Diamond,Pentagonal,Hexagonal,Heptagonal,Octagonal,Decagonal,Ellipse,Star5,Star6,Star7,Star8,Star10
}

public class EnumToGeometryConverter : IValueConverter
{
    public object Convert(object value,Type targetType,object parameter,CultureInfo culture)
    {
        GeometryEnum _enumGeometry;
        if (value != null)
            _enumGeometry = (GeometryEnum)Enum.Parse(typeof(GeometryEnum),value.ToString());
        else if (parameter != null)
            _enumGeometry = (GeometryEnum)Enum.Parse(typeof(GeometryEnum),parameter.ToString());
        else
            return null;
        switch (_enumGeometry)
        {
            case GeometryEnum.Triangle: return Geometry.Parse("M0.5,0 1,1 0,1 Z");
            case GeometryEnum.Ellipse: return new EllipseGeometry(new System.Windows.Point(0.5,0.5),0.5,0.5);
            case GeometryEnum.Rectangle: return new RectangleGeometry(new System.Windows.Rect(new System.Windows.Size(1,1)));
            case GeometryEnum.RoundedRectangle: return new RectangleGeometry(new System.Windows.Rect(new System.Windows.Size(1,1)),0.1d,0.1d);
        }
        return null;
    }

    public object ConvertBack(object value,CultureInfo culture)
    {
        return null;
    }
}

我想使用此转换器将每个枚举值转换为其等效的几何形状。我在程序的其他部分使用此转换没有任何问题。 但是当我在菜单项的Icon属性中使用它时,我看到只有最后一个菜单项具有Icon,其他菜单项都为空。

在xaml文件中,菜单项的代码如下:

 <ObjectDataProvider x:Key="DataGeometryTypeEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
    <ObjectDataProvider.MethodParameters>
        <x:Type TypeName="classes:GeometryEnum"/>
    </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>


    <MenuItem Header="Shape Type" Command="{x:Static tndcontrols:TndGraphCanvas.ComboBoxShapeRoutedCommand}"
              ItemsSource="{Binding Source={StaticResource DataGeometryTypeEnum}}"
              >
        <MenuItem.ItemContainerStyle>
            <Style TargetType="{x:Type MenuItem}">
                <Setter Property="Command" Value="{x:Static tndcontrols:TndGraphCanvas.ComboBoxShapeRoutedCommand}" />
                <Setter Property="CommandParameter" Value="{Binding}" />
                <Setter Property="Icon">
                    <Setter.Value>
                        <Image Width="16" Height="16">
                            <Image.Source>
                                <DrawingImage>
                                    <DrawingImage.Drawing>
                                        <GeometryDrawing Brush="#FF466280" Geometry="{Binding Converter={StaticResource EnumToGeometryConverter}}">
                                            <GeometryDrawing.Pen>
                                                <Pen Thickness="1" Brush="#FF212121"/>
                                            </GeometryDrawing.Pen>
                                        </GeometryDrawing>
                                    </DrawingImage.Drawing>
                                </DrawingImage>
                            </Image.Source>
                        </Image>
                    </Setter.Value>
                </Setter>
            </Style>
        </MenuItem.ItemContainerStyle>
        <MenuItem.Icon>
            <Image Source="Images/Icons/Shapes.ico" Width="16" Height="16"/>
        </MenuItem.Icon>
    </MenuItem>

enter image description here

解决方法

我经常使用字典转换器。 它提供了各种值的通用转换。 我认为这将适合您解决问题:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Windows.Data;

namespace Common
{
    /// <summary>A converter that converts a key to a dictionary value.</summary>
    public class DictionaryKeyToValueConverter : Dictionary<object,object>,IMultiValueConverter,IValueConverter
    {
        // The first element in the values parameter comes the key,the second - the dictionary.
        public object Convert(object[] values,Type targetType,object parameter,CultureInfo culture)
        {
            // If only the key is received,the converter dictionary is used.
            if (values.Length == 1)
            {

                if (TryGetValue(values[0],out object val))
                    return val;

            }
            // If more than one element came,then the key is extracted from the first,and the dictionary from the second.
            else if (values.Length > 1 && (values[1] is IDictionary dictionary) && (dictionary.Contains(values[0])))
            {
                return dictionary[values[0]];
            }
            return null;
        }

        // The dictionary key should come in the value parameter.
        public object Convert(object value,CultureInfo culture)
        {
            if (TryGetValue(value,out object val))
                return val;

            return null;
        }

        public object[] ConvertBack(object value,Type[] targetTypes,CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        public object ConvertBack(object value,CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

示例:

<Window x:Class="IconsMenu.IconMenuWind"
        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:IconsMenu"
        xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:comm="clr-namespace:Common"
        mc:Ignorable="d"
        Title="IconMenuWind" Height="450" Width="800">
    <Window.Resources>
        <ObjectDataProvider x:Key="DataGeometryTypeEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:GeometryEnum"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
        <comm:DictionaryKeyToValueConverter x:Key="EnumToImageConverter">
            <DrawingImage x:Key="{x:Static local:GeometryEnum.Triangle}">
                <DrawingImage.Drawing>
                    <GeometryDrawing Brush="#FF466280" Geometry="M 0.5 0 1,1 0,1 Z">
                        <GeometryDrawing.Pen>
                            <Pen Thickness="1" Brush="#FF212121"/>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>
                </DrawingImage.Drawing>
            </DrawingImage>
            <DrawingImage x:Key="{x:Static local:GeometryEnum.Ellipse}">
                <DrawingImage.Drawing>
                    <GeometryDrawing Brush="#FF466280">
                        <GeometryDrawing.Geometry>
                            <EllipseGeometry Center="0.5 0.5" RadiusX="0.5" RadiusY="0.5"/>
                        </GeometryDrawing.Geometry>
                        <GeometryDrawing.Pen>
                            <Pen Thickness="1" Brush="#FF212121"/>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>
                </DrawingImage.Drawing>
            </DrawingImage>
            <DrawingImage x:Key="{x:Static local:GeometryEnum.Rectangle}">
                <DrawingImage.Drawing>
                    <GeometryDrawing Brush="#FF466280">
                        <GeometryDrawing.Geometry>
                            <RectangleGeometry Rect="0,1,1"/>
                        </GeometryDrawing.Geometry>
                        <GeometryDrawing.Pen>
                            <Pen Thickness="1" Brush="#FF212121"/>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>
                </DrawingImage.Drawing>
            </DrawingImage>
            <DrawingImage x:Key="{x:Static local:GeometryEnum.RoundedRectangle}">
                <DrawingImage.Drawing>
                    <GeometryDrawing Brush="#FF466280">
                        <GeometryDrawing.Geometry>
                            <RectangleGeometry Rect="0,1" RadiusX="0.1" RadiusY="0.1"/>
                        </GeometryDrawing.Geometry>
                        <GeometryDrawing.Pen>
                            <Pen Thickness="1" Brush="#FF212121"/>
                        </GeometryDrawing.Pen>
                    </GeometryDrawing>
                </DrawingImage.Drawing>
            </DrawingImage>
        </comm:DictionaryKeyToValueConverter>
    </Window.Resources>
    <Grid>
        <ListBox ItemsSource="{Binding Mode=OneWay,Source={StaticResource DataGeometryTypeEnum}}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Grid x:Name="grid">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="{Binding ActualHeight,ElementName=grid,Mode=OneWay}"/>
                            <ColumnDefinition/>
                        </Grid.ColumnDefinitions>
                        <Image Source="{Binding Converter={StaticResource EnumToImageConverter},Mode=OneWay}"/>
                        <TextBlock Text="{Binding}" Grid.Column="1"/>
                    </Grid>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

或者像这样:

<Window.Resources>
    <ObjectDataProvider x:Key="DataGeometryTypeEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:GeometryEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    <comm:DictionaryKeyToValueConverter x:Key="EnumToImageConverter">
        <Geometry x:Key="{x:Static local:GeometryEnum.Triangle}">M 0.5 0 1,1 Z</Geometry>
        <EllipseGeometry x:Key="{x:Static local:GeometryEnum.Ellipse}" Center="0.5 0.5" RadiusX="0.5" RadiusY="0.5"/>
        <RectangleGeometry x:Key="{x:Static local:GeometryEnum.Rectangle}" Rect="0,1"/>
        <RectangleGeometry x:Key="{x:Static local:GeometryEnum.RoundedRectangle}" Rect="0,1" RadiusX="0.1" RadiusY="0.1"/>
    </comm:DictionaryKeyToValueConverter>
</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Mode=OneWay,Source={StaticResource DataGeometryTypeEnum}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid x:Name="grid">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="{Binding ActualHeight,Mode=OneWay}"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Image>
                        <Image.Source>
                            <DrawingImage>
                                <DrawingImage.Drawing>
                                    <GeometryDrawing Brush="#FF466280" Geometry="{Binding Converter={StaticResource EnumToImageConverter},Mode=OneWay}" >
                                        <GeometryDrawing.Pen>
                                            <Pen Thickness="1" Brush="#FF212121"/>
                                        </GeometryDrawing.Pen>
                                    </GeometryDrawing>
                                </DrawingImage.Drawing>
                            </DrawingImage>
                        </Image.Source>
                    </Image>
                    <TextBlock Text="{Binding}" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

使用多个转换器实例与多个枚举一起使用的示例。

添加的枚举:

public enum ColorsEnum
{
    Black,Green
}

XAML:

<Window.Resources>
    <ObjectDataProvider x:Key="DataGeometryTypeEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:GeometryEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
    <ObjectDataProvider x:Key="DataColorsTypeEnum" MethodName="GetValues"
                        ObjectType="{x:Type System:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:ColorsEnum"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>

    <comm:DictionaryKeyToValueConverter x:Key="DictionaryConverter">
        <Geometry x:Key="{x:Static local:GeometryEnum.Triangle}">M 0.5 0 1,1" RadiusX="0.1" RadiusY="0.1"/>
        <SolidColorBrush x:Key="{x:Static local:ColorsEnum.Black}" Color="Black"/>
        <SolidColorBrush x:Key="{x:Static local:ColorsEnum.Green}" Color="Green"/>
    </comm:DictionaryKeyToValueConverter>
    <comm:DictionaryKeyToValueConverter x:Key="ForegroundConverter">
        <SolidColorBrush x:Key="{x:Static local:GeometryEnum.Triangle}" Color="Gray" />
        <SolidColorBrush x:Key="{x:Static local:GeometryEnum.Ellipse}" Color="Green"/>
        <SolidColorBrush x:Key="{x:Static local:GeometryEnum.Rectangle}" Color="Blue"/>
        <SolidColorBrush x:Key="{x:Static local:GeometryEnum.RoundedRectangle}" Color="Coral"/>
        <SolidColorBrush x:Key="{x:Static local:ColorsEnum.Black}" Color="LightGray"/>
        <SolidColorBrush x:Key="{x:Static local:ColorsEnum.Green}" Color="Yellow"/>
    </comm:DictionaryKeyToValueConverter>
</Window.Resources>
<Grid>
    <ListBox ItemsSource="{Binding Mode=OneWay,Source={StaticResource DataGeometryTypeEnum}}"
             HorizontalAlignment="Left">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Grid x:Name="grid">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="{Binding ActualHeight,Mode=OneWay}"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <Image>
                        <Image.Source>
                            <DrawingImage>
                                <DrawingImage.Drawing>
                                    <GeometryDrawing Brush="#FF466280"
                                                     Geometry="{Binding Converter={StaticResource DictionaryConverter},Mode=OneWay}" >
                                        <GeometryDrawing.Pen>
                                            <Pen Thickness="1" Brush="{Binding Converter={StaticResource ForegroundConverter}}"/>
                                        </GeometryDrawing.Pen>
                                    </GeometryDrawing>
                                </DrawingImage.Drawing>
                            </DrawingImage>
                        </Image.Source>
                    </Image>
                    <TextBlock Text="{Binding}" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <ListBox ItemsSource="{Binding Mode=OneWay,Source={StaticResource DataColorsTypeEnum}}" HorizontalAlignment="Center">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding}"
                           Background="{Binding Converter={StaticResource DictionaryConverter}}"
                           Foreground="{Binding Converter={StaticResource ForegroundConverter}}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    <ListBox ItemsSource="{Binding Keys,Source={StaticResource DictionaryConverter}}" HorizontalAlignment="Right"/>
</Grid>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-