WPF
WPF Dialog Box/ ValidationRule 파일열기 유효성검사
스티커
2010. 10. 20. 11:05
참고 URL : http://msdn.microsoft.com/en-us/library/aa969773.aspx
별다른건 없고 그냥 Microsoft.Win32 네임스페이스 참조만 해주고 예전처럼 사용하면 됩니다.
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.FileName = "Command"; // Default file name
dlg.DefaultExt = ".exe"; // Default file extension
dlg.Filter = "Text documents (.exe)|*.exe"; // Filter files by extension
// Show open file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process open file dialog box results
if (result == true)
{
// Open document
string filename = dlg.FileName;
}
WPF 컨트롤의 유효성을 검사할려면 규칙만들고 바인딩 연결(유효성 검사 규칙은 ValidationRule)
규칙만들고
using System.Globalization; using System.Windows.Controls; namespace SDKSample { public class MarginValidationRule : ValidationRule { double minMargin; double maxMargin; public double MinMargin { get { return this.minMargin; } set { this.minMargin = value; } } public double MaxMargin { get { return this.maxMargin; } set { this.maxMargin = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { double margin; // Is a number? if (!double.TryParse((string)value, out margin)) { return new ValidationResult(false, "Not a number."); } // Is in range? if ((margin < this.minMargin) || (margin > this.maxMargin)) { string msg = string.Format("Margin must be between {0} and {1}.", this.minMargin, this.maxMargin); return new ValidationResult(false, msg); } // Number is valid return new ValidationResult(true, null); } } }
컨트롤에 연결하고
using System.Windows; // Window, RoutedEventArgs, IInputElement, DependencyObject using System.Windows.Controls; // Validation using System.Windows.Input; // Keyboard namespace SDKSample { public partial class MarginsDialogBox : Window { ... void okButton_Click(object sender, RoutedEventArgs e) { // Don't accept the dialog box if there is invalid data if (!IsValid(this)) return; ... } // Validate all dependency objects in a window bool IsValid(DependencyObject node) { // Check if dependency object was passed if (node != null) { // Check if dependency object is valid. // NOTE: Validation.GetHasError works for controls that have validation rules attached bool isValid = !Validation.GetHasError(node); if (!isValid) { // If the dependency object is invalid, and it can receive the focus, // set the focus if (node is IInputElement) Keyboard.Focus((IInputElement)node); return false; } } // If this dependency object is valid, check all child dependency objects foreach (object subnode in LogicalTreeHelper.GetChildren(node)) { if (subnode is DependencyObject) { // If a child dependency object is invalid, return false immediately, // otherwise keep checking if (IsValid((DependencyObject)subnode) == false) return false; } } // All dependency objects are valid return true; } } }
아 너무 귀찮다 ㅋ 그냥 if( this.text ==””){ } 이런씩으로 올드하게 하면 안되나? ㅎ