问题
当我尝试在WPF数据网格中显示一个枚举类型时,自动分配的组合框不会正确显示。
当数据网格首次显示时,“enum”根本没有显示出来,而其他类型(如“bool”和“double”)则按预期显示:
但如果我点击枚举单元格,就会看到组合框出现:
如何立即让组合框出现?
定义
在我的确切情况中,我只想显示PathSettings
列表。
PathSetting
只是一堆像这样定义的数据:
public class PathSettings
{
public bool IsSelected { get; set; }
public PathType PathType { get; set; }
public double Gain { get; set; }
}
其中PathType
是一些枚举值:
public enum PathType
{
Direct,
Amplified,
Load
}
假设我想要展示下列列表:
var tests = new List<PathSettings>
{
new PathSettings { IsSelected = false, PathType = PathType.Direct, Gain = 2.0 },
new PathSettings { IsSelected = true, PathType = PathType.Amplified, Gain = 2.5 },
new PathSettings { IsSelected = false, PathType = PathType.Load, Gain = 0.9 },
};
编码试图
我首先创建了一个 ViewAdapter
类,将我的 List
转换为一些 DataView
对象:
public class ViewAdapter
{
private static IEnumerable<PathSettings> buildDummyEntries()
{
return new List<PathSettings>
{
new PathSettings { IsSelected = false, PathType = PathType.Direct, Gain = 2.0 },
new PathSettings { IsSelected = true, PathType = PathType.Amplified, Gain = 2.5 },
new PathSettings { IsSelected = false, PathType = PathType.Load, Gain = 0.9 },
};
}
public ViewAdapter() : this(buildDummyEntries())
{
}
public ViewAdapter(IEnumerable<PathSettings> settings)
{
if (settings == null) { throw new ArgumentNullException(); }
// 1) Transform to cell collection
var cells = new ObservableCollection<ObservableCollection<object>>();
foreach (var s in settings)
{
cells.Add(new ObservableCollection<object>
{
s.IsSelected,
s.PathType,
s.Gain,
});
}
// 2) Transform to datatable
var dataTable = new DataTable();
dataTable.Columns.Add("IsSelected", typeof(bool));
dataTable.Columns.Add("PathType", typeof(PathType));
dataTable.Columns.Add("Gain", typeof(double));
foreach (var t in settings)
{
dataTable.Rows.Add(dataTable.NewRow());
}
// 3) Transform to data view and feed with cells
Settings = new DataView(dataTable);
for (var i = 0; i < settings.Count(); i++)
{
for (var j = 0; j < cells[i].Count; j++)
{
Settings[i][j] = cells[i][j];
}
}
}
public DataView Settings
{
get;
private set;
}
}
我使用它来填充我的DataGrid
的ItemsSource
:
<Window x:Class="EnumInDataGrid.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:EnumInDataGrid"
Title="MainWindow"
mc:Ignorable="d"
d:Height="350" d:Width="525"
d:DataContext="{d:DesignInstance Type=local:ViewAdapter, IsDesignTimeCreatable=True}"
d:DesignHeight="239" d:DesignWidth="308">
<Window.DataContext>
<local:ViewAdapter />
</Window.DataContext>
<Grid>
<DataGrid
ItemsSource="{Binding Settings}"
CanUserAddRows="False"
CanUserDeleteRows="False"
CanUserReorderColumns="False"
CanUserResizeRows="False"
CanUserSortColumns="False"
SelectionMode="Single"
SelectionUnit="Cell"/>
</Grid>
</Window>