標籤:style blog http color os 檔案
以下內容適合像我一樣的新手!有什麼好的建議!還望大家指點!
如下:
第一步:先 建立檔案夾 CheckValueLibrary 在建立一個類 PhoneNumberCheck 用於驗證 此類繼承 ValidationRule 類!
PhoneNumberCheck 類代碼如下(Regex有錯,可借鑒方法):
<span style="font-size:14px;">namespace Demo1.CheckValueLibrary{ // public class PhoneNumberCheck<span style="color:#ff6600;">:ValidationRule</span> { public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { string PoneNumber = value.ToString(); bool rt= Regex.IsMatch(PoneNumber, "^[0-9]*$");// Regex(驗證是否為數字) if (!rt || PoneNumber.Length > 11) { return new ValidationResult(false,"請輸入正確的電話號碼"); } else { return new ValidationResult(true, null); } } }}</span>第二步:在表單中引用 驗證的命名空間 xmlns:CheckValue="clr-namespace:Demo1.CheckValueLibrary"
第三步:自訂錯誤提示模板樣式,代碼如下:
<span style="font-size:14px;"><Window.Resources> <Style TargetType="TextBox"> <!--錯誤模板--> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <Border CornerRadius="3" BorderBrush="Red" BorderThickness="1"> <!-- 若錯誤提示現在 在下方 去掉 Orientation="Horizontal" 即可 --> <StackPanel Orientation="Horizontal"> <AdornedElementPlaceholder x:Name="Adorned"/> <TextBlock Width="{TemplateBinding Width}" Foreground="Red"> <!--顯示錯誤提示內容--> <TextBlock.Text> <Binding ElementName="Adorned" Path="AdornedElement.(Validation.Errors)[0].ErrorContent"/> </TextBlock.Text> <!--錯誤提示字的的樣式--> <TextBlock.Effect> <DropShadowEffect Opacity="0.6" ShadowDepth="3" Color="Black"/> </TextBlock.Effect> </TextBlock> </StackPanel> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </Window.Resources></span>
第四步:在TextBox中 加入驗證,代碼如下:
<span style="font-size:14px;"><TextBox Margin="59,38,94,201"> <TextBox.Text> <Binding Path="PhoneNumber" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged"> <!--輸入驗證--> <Binding.ValidationRules> <CheckValue:PhoneNumberCheck></CheckValue:PhoneNumberCheck> </Binding.ValidationRules> </Binding> </TextBox.Text></TextBox></span>
OK!運行可看效果,根據所選加以改進!