using System;
|
using System.ComponentModel;
|
using System.Windows;
|
using System.Windows.Controls;
|
using Panuon.WPF.UI;
|
using Panuon.WPF.UI.Configurations;
|
|
namespace HMI.UI
|
{
|
public class FormGroupHelper
|
{
|
public static bool GetIsRequired(FormGroup fg)
|
{
|
return (bool)fg.GetValue(IsRequiredProperty);
|
}
|
|
public static void SetIsRequired(FormGroup fg, bool value)
|
{
|
fg.SetValue(IsRequiredProperty, value);
|
}
|
|
public static readonly DependencyProperty IsRequiredProperty =
|
DependencyProperty.RegisterAttached("IsRequired", typeof(bool), typeof(FormGroupHelper),
|
new PropertyMetadata(false, (d, e) =>
|
{
|
if (!(d is FormGroup fg)) return;
|
if ((bool)e.NewValue)
|
{
|
var style = Application.Current.FindResource("RequiredInputFormGroupStyle") as Style;
|
fg.Style = style;
|
}
|
else
|
{
|
var style = Application.Current.FindResource("RequiredInputFormGroupStyle") as Style;
|
fg.Style = style;
|
}
|
}));
|
|
|
public delegate bool ValidateMethodDelegate(object value, out string msg);
|
public static ValidateMethodDelegate GetValidateMethod(FormGroup fg)
|
{
|
return (ValidateMethodDelegate)fg.GetValue(ValidateMethodProperty);
|
}
|
|
public static void SetValidateMethod(FormGroup fg, ValidateMethodDelegate value)
|
{
|
fg.SetValue(ValidateMethodProperty, value);
|
}
|
|
public static readonly DependencyProperty ValidateMethodProperty =
|
DependencyProperty.RegisterAttached("ValidateMethod", typeof(ValidateMethodDelegate), typeof(FormGroupHelper),
|
new PropertyMetadata(null));
|
|
public static bool ValidateForm(StackPanel fgPanel)
|
{
|
if (fgPanel.Children == null) return true;
|
bool res = true;
|
foreach (var child in fgPanel.Children)
|
{
|
if (child is FormGroup fg)
|
{
|
object content = fg.Content;
|
object value = GetValidateValue(content);
|
if (GetIsRequired(fg) && string.IsNullOrEmpty(value.ToString()))
|
{
|
fg.ValidateResult = ValidateResult.Error;
|
fg.Message = $"{fg.Header}不能为空";
|
res = false;
|
}
|
else
|
{
|
ValidateMethodDelegate method = GetValidateMethod(fg);
|
if (method != null && !method(value, out string err))
|
{
|
fg.ValidateResult = ValidateResult.Error;
|
fg.Message = err;
|
res = false;
|
}
|
}
|
}
|
}
|
return res;
|
}
|
|
private static object GetValidateValue(object content)
|
{
|
if (content == null) return null;
|
if (content is UIElementCollection elementCollection)
|
return elementCollection.Count > 0 ? GetValidateValue(elementCollection[0]) : null;
|
if (content is TextBox tb) return tb.Text;
|
if (content is CheckBox cb) return cb.IsChecked;
|
if (content is ComboBox cBox) return cBox.Text;
|
|
if (content is Panel panel) return GetValidateValue(panel.Children);
|
return null;
|
}
|
}
|
}
|