【发布时间】:2014-10-17 06:22:37
【问题描述】:
我正在尝试使用绑定到字典的动态数据构建数据网格,但生成的数据网格包含空行。
XAML
<Grid x:Name="LayoutRoot" Background="White">
<sdk:DataGrid AutoGenerateColumns="False" Height="153" HorizontalAlignment="Left" Margin="0,75,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="400" />
</Grid>
CodeBehind.cs
Dictionary<string, object> d = new Dictionary<string, object>();
public MainPage()
{
InitializeComponent();
List<Dictionary<string, object>> theList = new List<Dictionary<string, object>>();
for(int i=0;i<10;i++)
{
d = new Dictionary<string, object>();
d.Add("columnName1", "John");
d.Add("columnName2", "Smith");
d.Add("columnName3", 29);
d.Add("columnName", 5.9);
theList.Add(d);
}
this.AddColumnToGrid(dataGrid1, (IEnumerable<Dictionary<string, object>>)theList);
dataGrid1.ItemsSource = theList;
}
private void AddColumnToGrid(DataGrid theGrid, IEnumerable<Dictionary<string, object>> IEnumDataList)
{
Dictionary<string, object> firstRow = (Dictionary<string, object>)IEnumDataList.FirstOrDefault();
foreach (KeyValuePair<string, object> pair in firstRow)
{
theGrid.Columns.Add(CreateColumn(pair.Key));
}
}
RowIndexConverter _rowIndexConverter = new RowIndexConverter();
private DataGridColumn CreateColumn(string property)
{
return new DataGridTextColumn()
{
CanUserSort = true,
Header = property,
SortMemberPath = property,
IsReadOnly = false,
Binding = new Binding()
{
Converter = _rowIndexConverter,
ConverterParameter = property,
Mode = BindingMode.OneWay
}
};
}
public class Row
{
private Dictionary<string, object> _data = new Dictionary<string, object>();
public object this[string index]
{
get { return _data[index]; }
set { _data[index] = value; }
}
}
public class RowIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
SilverlightApplication1.MainPage.Row row = value as SilverlightApplication1.MainPage.Row;
if (row == null)
{
return null;
}
string index = parameter as string;
return row[index];
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
【问题讨论】:
标签: c# wpf silverlight dictionary datagrid