You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
wcs_core/Sln.Wcs.UI/Views/Base/EntityEditWindow.axaml.cs

125 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
using Avalonia.Media;
using Sln.Wcs.UI.ViewModels.Base;
namespace Sln.Wcs.UI.Views.Base;
public partial class EntityEditWindow : Window
{
private object? _entity;
private TaskCompletionSource<bool>? _tcs;
public EntityEditWindow()
{
InitializeComponent();
CancelBtn.Click += (_, _) => CloseWith(false);
SaveBtn.Click += (_, _) => CloseWith(true);
}
public Task<bool> ShowDialog(object entity, List<FieldConfig> fields, bool isEdit, Window owner)
{
_entity = entity;
TitleText.Text = isEdit ? "编辑" : "新增";
BuildForm(fields);
_tcs = new TaskCompletionSource<bool>();
ShowDialog(owner);
return _tcs.Task;
}
private void BuildForm(List<FieldConfig> fields)
{
FormPanel.Children.Clear();
if (_entity is null) return;
var type = _entity.GetType();
foreach (var field in fields)
{
var prop = type.GetProperty(field.PropertyName);
if (prop is null) continue;
var value = prop.GetValue(_entity);
// 字段卡片
var cell = new Border
{
Width = 345,
Padding = new Thickness(12, 6),
Margin = new Thickness(0, 3),
};
var row = new Grid { ColumnDefinitions = new ColumnDefinitions("90,*") };
// 标签
var label = new TextBlock
{
Text = field.DisplayName,
FontSize = 12,
Foreground = Brush.Parse("#7B8FA8"),
VerticalAlignment = VerticalAlignment.Center,
};
row.Children.Add(label);
// 输入框
Control input;
if (field.FieldType == FieldType.CheckBox)
{
var cb = new CheckBox
{
IsChecked = value is int iv ? iv == 1 : (value as bool? ?? false),
IsEnabled = !field.IsReadOnly,
Foreground = Brush.Parse("#BCC8D6"),
VerticalAlignment = VerticalAlignment.Center,
};
cb.IsCheckedChanged += (_, _) =>
prop.SetValue(_entity, cb.IsChecked == true ? 1 : 0);
input = cb;
}
else
{
var tb = new TextBox
{
Text = value?.ToString() ?? "",
IsReadOnly = field.IsReadOnly,
Watermark = field.DisplayName,
Background = Brush.Parse("#0A0E14"),
Foreground = Brush.Parse("#DDE4F0"),
BorderBrush = Brush.Parse("#1A2F4A"),
BorderThickness = new Thickness(1),
CornerRadius = new CornerRadius(3),
Padding = new Thickness(8, 5),
FontSize = 12,
};
if (field.FieldType == FieldType.Number)
{
tb.TextChanged += (_, _) =>
{
if (int.TryParse(tb.Text, out var num))
prop.SetValue(_entity, num);
};
}
else
{
tb.TextChanged += (_, _) =>
prop.SetValue(_entity, tb.Text);
}
input = tb;
}
Grid.SetColumn(input, 1);
row.Children.Add(input);
cell.Child = row;
FormPanel.Children.Add(cell);
}
}
private void CloseWith(bool result)
{
_tcs?.TrySetResult(result);
Close();
}
}