将 ComboBox 的 DisplayMemberPath 绑定到字符串方法

Binding DisplayMemberPath of ComboBox to a string method

我需要获取完整的 OxyPlot 颜色集合,并将它们绑定到 DataGrid 的 ComboBox 以供将来选择。我设法做到了,但 ComboBox 中显示的名称是“0x00ff”、“0x0001”等。不幸的是,我只能获得实际的颜色名称("Green"、"Blue" 等) GetColorName() 方法。

DisplayMemberPath 与 public 属性完美配合,但当我尝试使用方法时,我的“0x00ff”被替换为空字符串。

有没有办法使用 DisplayMemberPath 中的方法来代替 public 属性 或者有其他方法吗?

我的 C# 代码:

using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Windows;

using OxyPlot;

namespace WpfTestApp
{
    public partial class MainWindow : Window
    {
        public class Data
        {
            public OxyColor Color { set; get; } = OxyColors.Automatic;
        }

        public ObservableCollection<OxyColor> Colors { set; get; } = new ObservableCollection<OxyColor>(
            typeof(OxyColors).GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.FieldType == typeof(OxyColor)).
            Select(f => f.GetValue(null)).Cast<OxyColor>().ToList());

        public ObservableCollection<Data> ColorData { set; get; } = new ObservableCollection<Data>();

        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;
        }
    }
}

我的XAML:

    <Window.Resources>
        <CollectionViewSource x:Key="ColorsItems" Source="{Binding Colors}" />
    </Window.Resources>

    <Grid>

        <DataGrid x:Name="dataGrid" ItemsSource="{Binding ColorData}" AutoGenerateColumns="False" CanUserSortColumns="False" Margin="44,29,507,230">

            <DataGrid.Columns>
                <DataGridComboBoxColumn Header="OxyColors" ItemsSource="{Binding Source={StaticResource ColorsItems}}"
                                        DisplayMemberPath="GetColorName"
                                        SelectedValueBinding="{Binding Color}"/>
            </DataGrid.Columns>

        </DataGrid>

    </Grid>

在 WPF 中,您不能直接绑定到方法。

使用 IValueConverter:

OxyColorToColorNameConverter.cs

[ValueConversion(typeof(OxyColor), typeof(string))]
class OxyColorToColorNameConverter : IValueConverter
{
  public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    => value is IEnumerable<OxyColor> colors
      ? colors.Select(color => color.GetColorName()) 
      : value is OxyColor color
          ? color.GetColorName()
          : Binding.DoNothing;

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    => value is IEnumerable<string> colorNames
      ? colorNames.Select(colorName => OxyColor.Parse(colorName)) 
      : value is string colorName 
          ? OxyColor.Parse(colorName)
          : Binding.DoNothing;
}

MainWindow.xaml

<Window>
  <Window.Reources>
    <OxyColorToColorNameConverter x:Key="OxyColorToColorNameConverter" />
  </Window.Resources>

  <DataGrid ItemsSource="{Binding ColorData}">
    <DataGrid.Columns>
      <DataGridComboBoxColumn Header="OxyColors">
        <DataGridComboBoxColumn.EditingElementStyle>
          <Style TargetType="ComboBox">
            <Setter Property="ItemsSource"
                    Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, 
                            Path=DataContext.Colors, 
                            Converter={StaticResource OxyColorToColorNameConverter}}" />
          </Style>
        </DataGridComboBoxColumn.EditingElementStyle>
        <DataGridComboBoxColumn.ElementStyle>
          <Style TargetType="ComboBox">
            <Setter Property="ItemsSource"
                    Value="{Binding RelativeSource={RelativeSource AncestorType=DataGrid}, 
                            Path=DataContext.Colors, 
                            Converter={StaticResource OxyColorToColorNameConverter}}" />
          </Style>
        </DataGridComboBoxColumn.ElementStyle>
      </DataGridComboBoxColumn>
    </DataGrid.Columns>
  </DataGrid>
</Window>

嗯,这比我预期的要容易。没有反射和转换

using OxyPlot;

namespace WpfTestApp
{
    /// <summary>
    /// Enum of all available OxyColors
    /// </summary>
    public enum OxyColorsEnum
    {
        Automatic,
        AliceBlue,
        AntiqueWhite,
        Aqua,
        Aquamarine,
        Azure,
        Beige,
        Bisque,
        Black,
        BlanchedAlmond,
        Blue,
        BlueViolet,
        Brown,
        BurlyWood,
        CadetBlue,
        Chartreuse,
        Chocolate,
        Coral,
        CornflowerBlue,
        Cornsilk,
        Crimson,
        Cyan,
        DarkBlue,
        DarkCyan,
        DarkGoldenrod,
        DarkGray,
        DarkGreen,
        DarkKhaki,
        DarkMagenta,
        DarkOliveGreen,
        DarkOrange,
        DarkOrchid,
        DarkRed,
        DarkSalmon,
        DarkSeaGreen,
        DarkSlateBlue,
        DarkSlateGray,
        DarkTurquoise,
        DarkViolet,
        DeepPink,
        DeepSkyBlue,
        DimGray,
        DodgerBlue,
        Firebrick,
        FloralWhite,
        ForestGreen,
        Fuchsia,
        Gainsboro,
        GhostWhite,
        Gold,
        Goldenrod,
        Gray,
        Green,
        GreenYellow,
        Honeydew,
        HotPink,
        IndianRed,
        Indigo,
        Ivory,
        Khaki,
        Lavender,
        LavenderBlush,
        LawnGreen,
        LemonChiffon,
        LightBlue,
        LightCoral,
        LightCyan,
        LightGoldenrodYellow,
        LightGray,
        LightGreen,
        LightPink,
        LightSalmon,
        LightSeaGreen,
        LightSkyBlue,
        LightSlateGray,
        LightSteelBlue,
        LightYellow,
        Lime,
        LimeGreen,
        Linen,
        Magenta,
        Maroon,
        MediumAquamarine,
        MediumBlue,
        MediumOrchid,
        MediumPurple,
        MediumSeaGreen,
        MediumSlateBlue,
        MediumSpringGreen,
        MediumTurquoise,
        MediumVioletRed,
        MidnightBlue,
        MintCream,
        MistyRose,
        Moccasin,
        NavajoWhite,
        Navy,
        OldLace,
        Olive,
        OliveDrab,
        Orange,
        OrangeRed,
        Orchid,
        PaleGoldenrod,
        PaleGreen,
        PaleTurquoise,
        PaleVioletRed,
        PapayaWhip,
        PeachPuff,
        Peru,
        Pink,
        Plum,
        PowderBlue,
        Purple,
        Red,
        RosyBrown,
        RoyalBlue,
        SaddleBrown,
        Salmon,
        SandyBrown,
        SeaGreen,
        SeaShell,
        Sienna,
        Silver,
        SkyBlue,
        SlateBlue,
        SlateGray,
        Snow,
        SpringGreen,
        SteelBlue,
        Tan,
        Teal,
        Thistle,
        Tomato,
        Transparent,
        Turquoise,
        Violet,
        Wheat,
        White,
        WhiteSmoke,
        Yellow,
        YellowGreen
    }

    /// <summary>
    /// Custom Oxy methods
    /// </summary>
    public static class OxyCustom
    {
        /// <summary>
        /// Return OxyColor by enum
        /// </summary>
        public static OxyColor ColorByEnum(OxyColorsEnum oxyEnum)
        {
            switch (oxyEnum)
            {
                case OxyColorsEnum.Automatic: return OxyColors.Automatic;
                case OxyColorsEnum.AliceBlue: return OxyColors.AliceBlue;
                case OxyColorsEnum.AntiqueWhite: return OxyColors.AntiqueWhite;
                case OxyColorsEnum.Aqua: return OxyColors.Aqua;
                case OxyColorsEnum.Aquamarine: return OxyColors.Aquamarine;
                case OxyColorsEnum.Azure: return OxyColors.Azure;
                case OxyColorsEnum.Beige: return OxyColors.Beige;
                case OxyColorsEnum.Bisque: return OxyColors.Bisque;
                case OxyColorsEnum.Black: return OxyColors.Black;
                case OxyColorsEnum.BlanchedAlmond: return OxyColors.BlanchedAlmond;
                case OxyColorsEnum.Blue: return OxyColors.Blue;
                case OxyColorsEnum.BlueViolet: return OxyColors.BlueViolet;
                case OxyColorsEnum.Brown: return OxyColors.Brown;
                case OxyColorsEnum.BurlyWood: return OxyColors.BurlyWood;
                case OxyColorsEnum.CadetBlue: return OxyColors.CadetBlue;
                case OxyColorsEnum.Chartreuse: return OxyColors.Chartreuse;
                case OxyColorsEnum.Chocolate: return OxyColors.Chocolate;
                case OxyColorsEnum.Coral: return OxyColors.Coral;
                case OxyColorsEnum.CornflowerBlue: return OxyColors.CornflowerBlue;
                case OxyColorsEnum.Cornsilk: return OxyColors.Cornsilk;
                case OxyColorsEnum.Crimson: return OxyColors.Crimson;
                case OxyColorsEnum.Cyan: return OxyColors.Cyan;
                case OxyColorsEnum.DarkBlue: return OxyColors.DarkBlue;
                case OxyColorsEnum.DarkCyan: return OxyColors.DarkCyan;
                case OxyColorsEnum.DarkGoldenrod: return OxyColors.DarkGoldenrod;
                case OxyColorsEnum.DarkGray: return OxyColors.DarkGray;
                case OxyColorsEnum.DarkGreen: return OxyColors.DarkGreen;
                case OxyColorsEnum.DarkKhaki: return OxyColors.DarkKhaki;
                case OxyColorsEnum.DarkMagenta: return OxyColors.DarkMagenta;
                case OxyColorsEnum.DarkOliveGreen: return OxyColors.DarkOliveGreen;
                case OxyColorsEnum.DarkOrange: return OxyColors.DarkOrange;
                case OxyColorsEnum.DarkOrchid: return OxyColors.DarkOrchid;
                case OxyColorsEnum.DarkRed: return OxyColors.DarkRed;
                case OxyColorsEnum.DarkSalmon: return OxyColors.DarkSalmon;
                case OxyColorsEnum.DarkSeaGreen: return OxyColors.DarkSeaGreen;
                case OxyColorsEnum.DarkSlateBlue: return OxyColors.DarkSlateBlue;
                case OxyColorsEnum.DarkSlateGray: return OxyColors.DarkSlateGray;
                case OxyColorsEnum.DarkTurquoise: return OxyColors.DarkTurquoise;
                case OxyColorsEnum.DarkViolet: return OxyColors.DarkViolet;
                case OxyColorsEnum.DeepPink: return OxyColors.DeepPink;
                case OxyColorsEnum.DeepSkyBlue: return OxyColors.DeepSkyBlue;
                case OxyColorsEnum.DimGray: return OxyColors.DimGray;
                case OxyColorsEnum.DodgerBlue: return OxyColors.DodgerBlue;
                case OxyColorsEnum.Firebrick: return OxyColors.Firebrick;
                case OxyColorsEnum.FloralWhite: return OxyColors.FloralWhite;
                case OxyColorsEnum.ForestGreen: return OxyColors.ForestGreen;
                case OxyColorsEnum.Fuchsia: return OxyColors.Fuchsia;
                case OxyColorsEnum.Gainsboro: return OxyColors.Gainsboro;
                case OxyColorsEnum.GhostWhite: return OxyColors.GhostWhite;
                case OxyColorsEnum.Gold: return OxyColors.Gold;
                case OxyColorsEnum.Goldenrod: return OxyColors.Goldenrod;
                case OxyColorsEnum.Gray: return OxyColors.Gray;
                case OxyColorsEnum.Green: return OxyColors.Green;
                case OxyColorsEnum.GreenYellow: return OxyColors.GreenYellow;
                case OxyColorsEnum.Honeydew: return OxyColors.Honeydew;
                case OxyColorsEnum.HotPink: return OxyColors.HotPink;
                case OxyColorsEnum.IndianRed: return OxyColors.IndianRed;
                case OxyColorsEnum.Indigo: return OxyColors.Indigo;
                case OxyColorsEnum.Ivory: return OxyColors.Ivory;
                case OxyColorsEnum.Khaki: return OxyColors.Khaki;
                case OxyColorsEnum.Lavender: return OxyColors.Lavender;
                case OxyColorsEnum.LavenderBlush: return OxyColors.LavenderBlush;
                case OxyColorsEnum.LawnGreen: return OxyColors.LawnGreen;
                case OxyColorsEnum.LemonChiffon: return OxyColors.LemonChiffon;
                case OxyColorsEnum.LightBlue: return OxyColors.LightBlue;
                case OxyColorsEnum.LightCoral: return OxyColors.LightCoral;
                case OxyColorsEnum.LightCyan: return OxyColors.LightCyan;
                case OxyColorsEnum.LightGoldenrodYellow: return OxyColors.LightGoldenrodYellow;
                case OxyColorsEnum.LightGray: return OxyColors.LightGray;
                case OxyColorsEnum.LightGreen: return OxyColors.LightGreen;
                case OxyColorsEnum.LightPink: return OxyColors.LightPink;
                case OxyColorsEnum.LightSalmon: return OxyColors.LightSalmon;
                case OxyColorsEnum.LightSeaGreen: return OxyColors.LightSeaGreen;
                case OxyColorsEnum.LightSkyBlue: return OxyColors.LightSkyBlue;
                case OxyColorsEnum.LightSlateGray: return OxyColors.LightSlateGray;
                case OxyColorsEnum.LightSteelBlue: return OxyColors.LightSteelBlue;
                case OxyColorsEnum.LightYellow: return OxyColors.LightYellow;
                case OxyColorsEnum.Lime: return OxyColors.Lime;
                case OxyColorsEnum.LimeGreen: return OxyColors.LimeGreen;
                case OxyColorsEnum.Linen: return OxyColors.Linen;
                case OxyColorsEnum.Magenta: return OxyColors.Magenta;
                case OxyColorsEnum.Maroon: return OxyColors.Maroon;
                case OxyColorsEnum.MediumAquamarine: return OxyColors.MediumAquamarine;
                case OxyColorsEnum.MediumBlue: return OxyColors.MediumBlue;
                case OxyColorsEnum.MediumOrchid: return OxyColors.MediumOrchid;
                case OxyColorsEnum.MediumPurple: return OxyColors.MediumPurple;
                case OxyColorsEnum.MediumSeaGreen: return OxyColors.MediumSeaGreen;
                case OxyColorsEnum.MediumSlateBlue: return OxyColors.MediumSlateBlue;
                case OxyColorsEnum.MediumSpringGreen: return OxyColors.MediumSpringGreen;
                case OxyColorsEnum.MediumTurquoise: return OxyColors.MediumTurquoise;
                case OxyColorsEnum.MediumVioletRed: return OxyColors.MediumVioletRed;
                case OxyColorsEnum.MidnightBlue: return OxyColors.MidnightBlue;
                case OxyColorsEnum.MintCream: return OxyColors.MintCream;
                case OxyColorsEnum.MistyRose: return OxyColors.MistyRose;
                case OxyColorsEnum.Moccasin: return OxyColors.Moccasin;
                case OxyColorsEnum.NavajoWhite: return OxyColors.NavajoWhite;
                case OxyColorsEnum.Navy: return OxyColors.Navy;
                case OxyColorsEnum.OldLace: return OxyColors.OldLace;
                case OxyColorsEnum.Olive: return OxyColors.Olive;
                case OxyColorsEnum.OliveDrab: return OxyColors.OliveDrab;
                case OxyColorsEnum.Orange: return OxyColors.Orange;
                case OxyColorsEnum.OrangeRed: return OxyColors.OrangeRed;
                case OxyColorsEnum.Orchid: return OxyColors.Orchid;
                case OxyColorsEnum.PaleGoldenrod: return OxyColors.PaleGoldenrod;
                case OxyColorsEnum.PaleGreen: return OxyColors.PaleGreen;
                case OxyColorsEnum.PaleTurquoise: return OxyColors.PaleTurquoise;
                case OxyColorsEnum.PaleVioletRed: return OxyColors.PaleVioletRed;
                case OxyColorsEnum.PapayaWhip: return OxyColors.PapayaWhip;
                case OxyColorsEnum.PeachPuff: return OxyColors.PeachPuff;
                case OxyColorsEnum.Peru: return OxyColors.Peru;
                case OxyColorsEnum.Pink: return OxyColors.Pink;
                case OxyColorsEnum.Plum: return OxyColors.Plum;
                case OxyColorsEnum.PowderBlue: return OxyColors.PowderBlue;
                case OxyColorsEnum.Purple: return OxyColors.Purple;
                case OxyColorsEnum.Red: return OxyColors.Red;
                case OxyColorsEnum.RosyBrown: return OxyColors.RosyBrown;
                case OxyColorsEnum.RoyalBlue: return OxyColors.RoyalBlue;
                case OxyColorsEnum.SaddleBrown: return OxyColors.SaddleBrown;
                case OxyColorsEnum.Salmon: return OxyColors.Salmon;
                case OxyColorsEnum.SandyBrown: return OxyColors.SandyBrown;
                case OxyColorsEnum.SeaGreen: return OxyColors.SeaGreen;
                case OxyColorsEnum.SeaShell: return OxyColors.SeaShell;
                case OxyColorsEnum.Sienna: return OxyColors.Sienna;
                case OxyColorsEnum.Silver: return OxyColors.Silver;
                case OxyColorsEnum.SkyBlue: return OxyColors.SkyBlue;
                case OxyColorsEnum.SlateBlue: return OxyColors.SlateBlue;
                case OxyColorsEnum.SlateGray: return OxyColors.SlateGray;
                case OxyColorsEnum.Snow: return OxyColors.Snow;
                case OxyColorsEnum.SpringGreen: return OxyColors.SpringGreen;
                case OxyColorsEnum.SteelBlue: return OxyColors.SteelBlue;
                case OxyColorsEnum.Tan: return OxyColors.Tan;
                case OxyColorsEnum.Teal: return OxyColors.Teal;
                case OxyColorsEnum.Thistle: return OxyColors.Thistle;
                case OxyColorsEnum.Tomato: return OxyColors.Tomato;
                case OxyColorsEnum.Transparent: return OxyColors.Transparent;
                case OxyColorsEnum.Turquoise: return OxyColors.Turquoise;
                case OxyColorsEnum.Violet: return OxyColors.Violet;
                case OxyColorsEnum.Wheat: return OxyColors.Wheat;
                case OxyColorsEnum.White: return OxyColors.White;
                case OxyColorsEnum.WhiteSmoke: return OxyColors.WhiteSmoke;
                case OxyColorsEnum.Yellow: return OxyColors.Yellow;
                case OxyColorsEnum.YellowGreen: return OxyColors.YellowGreen;
            }

            return OxyColors.Undefined;
        }
    }
}