效果图:
前端代码:
<Window x:Class="WPFDemo.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:WPFDemo" xmlns:core="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800"> <Window.Resources> <ObjectDataProvider x:Key="SexEnumKey" MethodName="GetValues" ObjectType="{x:Type core:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type Type="local:SexEnum"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <Grid> <DataGrid Name="DG1" ItemsSource="{Binding}" CanUserAddRows="False" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridComboBoxColumn Header="性别" SelectedItemBinding="{Binding Sex}" ItemsSource="{Binding Source={StaticResource SexEnumKey}}"></DataGridComboBoxColumn> </DataGrid.Columns> </DataGrid> </Grid> </Window>
后端代码:
using System.Collections.ObjectModel; using System.Windows; namespace WPFDemo { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { ObservableCollection<DTO> list = new ObservableCollection<DTO>(); public MainWindow() { InitializeComponent(); for (int i = 0; i < 5; i++) { list.Add(new DTO() { Sex = i == 0 ? SexEnum.boy : SexEnum.girl }); } DG1.DataContext = list; } } public enum SexEnum { boy, girl } public class DTO { public SexEnum Sex { get; set; } } }