Maui devexpress DataGridView - Привязка с пользовательским динамическим датом данныхC#

Место общения программистов C#
Anonymous
Maui devexpress DataGridView - Привязка с пользовательским динамическим датом данных

Сообщение Anonymous »

Я пытаюсь создать DataGridView, используя DeVexPress Toolkit для Maui, но просто не могу сделать это правильно. У меня есть пользовательская структура данных, которую я должен придерживаться и хочу связать столбцы с полями в моих данных.public class Form
{
// Attributes
public List RowList { get; set; }

public Form()
{
this.RowList = new();
this.RowList.Add(new Row());
}
}

public class Row
{
// Attributes
public List ColumnList { get; set; }

public Row()
{
this.ColumnList = new();
this.ColumnList.Add(new Column() { ColumnName = "Personal Details" });
this.ColumnList.Add(new Column() { ColumnName = "Products" });
this.ColumnList.Add(new Column() { ColumnName = "Employees" });
}
}

public class Column
{
// Attributes
public long ColumnId { get; set; }
public string ColumnName { get; set; }
public List RecordList { get; set; }

public Column()
{
this.RecordList = new();
}
}

public class Record
{
// Attributes
public List FieldList { get; set; }

public Record()
{
this.FieldList = new();
}
}

public class Field
{
public long FieldId { get; set; }
public string FieldLabel { get; set; }
public object Value { get; set; }
}
< /code>
А вот фрагмент образцов данных, которые заполняются в объекты: < /p>
this.RowList[0].ColumnList[0].RecordList.Add(new Record()
{
FieldList = new List
{
new Field { FieldId = 1, FieldLabel = "Name", Value = "Corne" },
new Field { FieldId = 2, FieldLabel = "Surname", Value = "Ackerman" },
new Field { FieldId = 3, FieldLabel = "Age", Value = 23 },
new Field { FieldId = 4, FieldLabel = "Email", Value = "corne@test.com" }
}
});

DataGridView может быть связан непосредственно с элементом -сайте, и я попытался привязать его с несколькими частями объекта, которые я создал форму формы = new (); , а затем я вкладываю образцы данных. При добавлении столбцов я попытался установить там DataBindings, но ничего, что я делал, казалось, не сработало. Проблема в том, что база данных не знает, как перейти в recordlist []. Fieldlist []. Value , я не могу сказать, что «вы-записи 2 и поле 4, так что перейдите в recordlist [2] .fieldlist [3]. помешать мне сделать что-то более простое.void setupGrids(MainPageViewModel vm)
{
// Iterate through columns
foreach (var col in vm.Form.RowList[0].ColumnList)
{
// Create new grid with default properties
DataGridView grid = new()
{
ReduceHeightToContent = true,
Margin = new Thickness(0, 0, 0, 20),
BorderThickness = new Thickness(2),
EditorShowMode = EditorShowMode.DoubleTap,
AllowDragDropRows = true,
AutoGenerateColumnsMode = AutoGenerateColumnsMode.Auto,
};

//Add label with column name
Label label = new()
{
Text = col.ColumnName,
FontSize = 20,
FontAttributes = FontAttributes.Bold,
Margin = new Thickness(0, 5, 0, 10),
};
labels.Add(label);

// Iterate over records and fields to add relevant column types to grid
// Goes through all records in case some fields are not present in all records (ex. fields added later)
// Iterate over fields to add relevant column types to grid
foreach (var recordList in col.RecordList)
{
// Iterate through fields
foreach (var field in recordList.FieldList)
{
// Check if column hasn't been added yet
if (grid.Columns.FirstOrDefault(c => c.FieldName == field.FieldLabel) == null)
{
// Calculate width of column based on length of data and ColumnName
int width = field.Value.ToString().Length * 13;
int titleWidth = field.FieldLabel.ToString().Length * 13;
width = width < 100 ? 100 : width;
width = titleWidth > width ? titleWidth : width;

// Check data type and set column type accordingly
if (field.Value.GetType() == typeof(int))
{
grid.Columns.Add(new NumberColumn()
{
FieldName = field.FieldLabel,
Caption = field.FieldLabel,
MinWidth = width,
});
}
else if (field.Value.GetType() == typeof(DateTime))
{
grid.Columns.Add(new DateColumn()
{
FieldName = field.FieldLabel,
Caption = field.FieldLabel,
MinWidth = width,
});
}
else if (field.Value.GetType() == typeof(bool))
{
grid.Columns.Add(new CheckBoxColumn()
{
FieldName = field.FieldLabel,
Caption = field.FieldLabel,
MinWidth = width,
});
}
else if (field.Value.GetType() == typeof(decimal) || //All number types
field.Value.GetType() == typeof(long) ||
field.Value.GetType() == typeof(int) ||
field.Value.GetType() == typeof(short) |
field.Value.GetType() == typeof(float) ||
field.Value.GetType() == typeof(double))
{
grid.Columns.Add(new NumberColumn()
{
FieldName = field.FieldLabel,
Caption = field.FieldLabel,
MinWidth = width,
BindingContext = col.RecordList[0],
});
}
else
{
grid.Columns.Add(new TextColumn()
{
FieldName = field.FieldLabel,
Caption = field.FieldLabel,
MinWidth = width,
BindingContext = col.RecordList[0].FieldList[0],

});
}
}
}
}

// Set Source
//grid.ItemsSource = vm.getTable(col);
grid.ItemsSource = col.RecordList;
vm.GridList.Add(grid);
} // foreach column
}

private void addGridsToView(MainPageViewModel vm)
{
int c = 0;

// Iterate over gridList and add each grid to the stack layout
foreach (var grid in vm.GridList)
{
int i = 0;
//Apply additional formatting to headers
grid.Columns.ForEach(c =>
{
c.HeaderFontSize = 17;
c.HeaderBackgroundColor = Microsoft.Maui.Graphics.Color.FromRgba(173, 216, 230, 255);
c.HeaderFontAttributes = FontAttributes.Bold;
//c.SetBinding(TitleProperty, "FieldList.Field.FieldLabel");
//c.SetBinding(ContentProperty, new Binding("Value"));
//c.SetBinding(TitleProperty, new Binding("FieldName"));
//c.SetBinding(GridColumn.BindingContextProperty, "FieldList.Value.Value");
});

stack.Children.Add(labels[c++]);
stack.Children.Add(grid);
}
}
< /code>
Мне нужно сохранить все это динамично. Метод setBinding () - это то, что я думаю, что мне нужно использовать, но в сочетании с ним BindingContext . Я установил контекст в список записей , так как именно там обнаружены все данные, которые необходимо отобразить. Привязка данных должна быть двусторонней. class = "lang-cs prettyprint-override">BindingContext = col.RecordList;
< /code>
(я думаю, что это ближе всего к решению)BindingContext = new Binding("RecordList");`
BindingContext = col.RecordList[0].FieldList[0];
< /code>
(даже пробовал индексы жесткого кодирования)//c.SetBinding(TitleProperty, "FieldList.Field.FieldLabel");

//c.SetBinding(TitleProperty, "FieldList\[\*\].value");

//c.SetBinding(ContentProperty, new Binding("Value"));

//c.SetBinding(TitleProperty, new Binding("FieldName"));

//c.SetBinding(GridColumn.BindingContextProperty, "RecordList\[\**\].FieldList\[\**\].Value");


Подробнее здесь: https://stackoverflow.com/questions/782 ... c-datatype

Вернуться в «C#»