using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel;
using System.Text.RegularExpressions;
namespace SLInterop
{
public class DataBindClass : INotifyPropertyChanged
{
#region 統一編號,示範自訂檢核
private string companyId;
public string CompanyId {
get { return companyId; }
set
{
companyId = value;
string chkMsg =
ValidateHelper.ValidateCompanyId(value);
if (chkMsg.Length > 0)
{
//若無效時強迫清空可加入以下兩行
companyId = "";
NotifyPropertyChanged("CompanyId");
//抛出錯誤訊息
throw new ValidationException(chkMsg);
}
NotifyPropertyChanged("CompanyId");
}
}
#endregion
#region 識別碼,示範Data Annontation
//利用宣告加上檢核條件
private string id;
[Required(ErrorMessage="識別碼不可空白!")]
[StringLength(5, MinimumLength=3,
ErrorMessage="識別碼需為3-5碼!")]
public string Id
{
get { return id; }
set
{
id = value;
//呼叫Validator.ValidateProperty進行檢核
Validate(value, "Id");
NotifyPropertyChanged("Id");
}
}
#endregion
#region Annotation 檢核共用函數
//REF: http://msdn.microsoft.com/en-us/magazine/ee335695.aspx
protected void Validate(object value, string propertyName)
{
Validator.ValidateProperty(value,
new ValidationContext(this, null, null)
{
MemberName = propertyName
});
}
#endregion
#region 屬性值改變通知共用函數,TwoWay Binding必備
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
#endregion
}
#region 統編檢查
public static class ValidateHelper
{
static byte[] companyIdChkFac = { 1, 2, 1, 2, 1, 2, 4, 1 };
public static string ValidateCompanyId(string id)
{
//REF: http://herolin.mine.nu/entry/is-valid-TW-company-ID
//檢核是否為有效統編
string errMsg = "";
if (string.IsNullOrEmpty(id)) return errMsg;
if (!Regex.IsMatch(id, "\\d{8}"))
errMsg = "統編應為8位數字!";
else
{
int sum = 0;
for (int i = 0; i < 8; i++)
{
int d = (id[i] - 48) * companyIdChkFac[i];
sum += d / 10 + d % 10;
}
if (
!(sum % 10 == 0 ||
id[6] == '7' && (sum + 1) % 10 == 0)
)
errMsg = "統編檢查碼不符!";
}
return errMsg;
}
}
#endregion
public partial class MainPage : UserControl
{
//設定TextBox TwoWay Binding
private void SetTextBoxBinding(
TextBox txt, object bindTarget, string propName)
{
Binding bind = new Binding();
bind.Mode = BindingMode.TwoWay;
bind.Path = new PropertyPath(propName);
bind.Source = bindTarget;
bind.NotifyOnValidationError = true;
bind.ValidatesOnExceptions = true;
txt.SetBinding(TextBox.TextProperty, bind);
}
public MainPage()
{
InitializeComponent();
DataBindClass bdc = new DataBindClass();
SetTextBoxBinding(txtCmpId, bdc, "CompanyId");
SetTextBoxBinding(txtId, bdc, "Id");
}
}
}