我已经在 SO 上潜伏了很长时间,直到最近才决定建立一个帐户。我花了很多时间试图解决这个我一直没有询问的问题,但我就在这里。
我正在努力实现的目标:
我有一个字符串列表,例如:Mango、Banana、Melon(我们称之为水果),我想将其显示为 XAML (WPF) 中的表格,其中它在左侧和右侧显示为行值将是组合框,允许用户选择一个值。我目前陷入了这个问题的显示部分。我决定使用 DataGrid 来显示列表,后面的代码将执行数据绑定。
这是它的 XAML 部分:
<DataGrid x:Name="FruitDataGrid" Height="265" VerticalAlignment="Center" Margin="-7,8,-2,-6" HorizontalAlignment="Left" Width="1188" AutoGenerateColumns="False">
<!-- If AutoGenerateColumns was true only the length is displayed.-->
<DataGrid.Columns>
<DataGridTextColumn x:Name="fruitsDisplay" Header="Fruits" MinWidth="450" IsReadOnly="True" />
<DataGridComboBoxColumn Header="Number of Boxes" MinWidth ="200" CanUserResize="True" Width="*"></DataGridComboBoxColumn>
</DataGrid.Columns>
到目前为止,代码隐藏非常简单,经过多次尝试,这是最新的。
private void populateFruitList()
{
FruitDataGrid.DataContext = fruitDataTable;
//Binds a datatable instance to the datagrid, does not display anything.
}
我一直在尝试:
将字符串列表转换为可观察集合或可枚举,然后执行 FruitDataGrid.itemsource =fruitsObservable;
上面的方法是有效的,只不过它只会显示每个字符串值的长度(如果 autogeneratecolumns 为 true),这不是我想要的。如果 autogeneratecolumns 为 false,那么我可以看到显示的行,但看不到字符串值。
我也尝试使用DataView或DataGridView,但我未能在XAML中定义它,VS2012说没有这样的事情。
我一直在尝试进行数据绑定以及MSDN 文章 https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh464965.aspx说,但 VS2012 从未设法正确绑定到列表。
然后,我尝试将列表更改为数据表并[使用此处指定的 datagridview,但 XAML 再次告诉我它不是有效的类][2]。我也知道 datagridview 可能会对性能产生影响,但此时我只想真正显示一个表格。
我还看到一些教程使用 DataGrid.datasource 方法,但这不在我想要的 DataGrid 中,我认为它是一个不同的类? (我尝试使用的 DataGrid 是 System.Windows.Controls.DataGrid,另一个位于 Windows 窗体中 [如此处所示][3])
再次感谢您花时间调查此事。
EDIT
尝试以这种方式绑定到 XAML 中的列表:
<DataGrid x:Name="FruitDataGrid" Height="265" VerticalAlignment="Center" Margin="-7,8,-2,-6" HorizontalAlignment="Left" Width="1188" AutoGenerateColumns="False" ItemsSource="fruitDataList">
我在 XAML 中收到错误“IEnumerable 的类型转换器不支持从字符串转换”,我认为这是因为我做错了。不过,该表现在显示了很多空行。
尝试 ItemSsource="{Binding FruitDataList}" (其中 FruitDataList 是一个列表)会产生一个空白表,并且 VS 中会出现 BindingExpression 路径错误的错误。