BITKit/Packages/Runtime/UX/Core/UXTable.cs

101 lines
3.0 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
using Cysharp.Threading.Tasks;
using System.Data;
using System.Linq;
namespace BITKit.UX
{
public class UXTable : UXElement<VisualElement>, IProvider<DataTable>
{
public int createTableTimes = 0;
Label[,] labelTable = new Label[0, 0];
public new DataTable Get()
{
return null;
}
public async void Set(DataTable t)
{
try
{
await UniTask.SwitchToMainThread(cancellationToken);
if (labelTable.GetLength(0) != t.Rows.Count)
{
CreateDataTable();
}
t.Rows.Count.ForEach(row =>
{
t.Columns.Count.ForEach(col =>
{
var value = t.Rows[row][col] as string;
var label = labelTable[row, col];
label.text = value;
});
});
t.Dispose();
}
catch (System.Exception e)
{
if (e is OperationCanceledException)
{
}
else
{
Debug.LogException(e);
}
}
void CreateDataTable()
{
var width = visualElement.layout.width / t.Columns.Count;
int rowCount = 0;
int colCount = 0;
visualElement.Clear();
visualElement.style.flexDirection = new(FlexDirection.Column);
labelTable = new Label[t.Rows.Count, t.Columns.Count];
foreach (DataRow row in t.Rows)
{
VisualElement element = new();
var style = element.style;
style.flexDirection = FlexDirection.Row;
SetUpStyle(element.style);
colCount = 0;
foreach (DataColumn col in t.Columns)
{
var value = row[col];
var label = new Label(value?.ToString());
//label.style.width = width;
SetUpStyle(label.style);
element.Add(label);
labelTable[rowCount, colCount] = label;
colCount++;
}
rowCount++;
visualElement.Add(element);
}
createTableTimes++;
}
}
void SetUpStyle(IStyle style)
{
style.marginTop = 0;
style.marginLeft = 0;
style.marginRight = 0;
style.marginBottom = 0;
style.paddingTop = 0;
style.paddingLeft = 0;
style.paddingRight = 0;
style.paddingBottom = 0;
}
}
}