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

121 lines
3.6 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;
Title = 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 = 340,
Padding = new Thickness(0, 4, 10, 4),
};
var row = new Grid
{
ColumnDefinitions = new ColumnDefinitions("100,*"),
};
var label = new TextBlock
{
Text = field.DisplayName + ":",
FontSize = 12,
Foreground = Brush.Parse("#8B9BB5"),
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("#DDE4F0"),
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("#0C1622"),
Foreground = Brush.Parse("#DDE4F0"),
BorderBrush = Brush.Parse("#1A2F4A"),
};
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();
}
}