2011-01-01 34 views
5

Hi Tôi cần xác thực một số hộp văn bản trong ứng dụng của mình. Tôi đã từ chối sử dụng quy tắc xác thực "DataErrorValidationRule". Đó là lý do tại sao trong lớp của tôi, tôi đã triển khai giao diện IDataErrorInfo và đã viết các hàm aproperiate. Trong mã xaml của tôi, tôi đã thêm các quy tắc ràng buộc và xác thực vào hộp văn bảnwpf - xác thực - cách hiển thị chú giải công cụ và tắt nút "chạy"

<TextBox x:Name="txtName" Grid.Column="3" Grid.Row="1" TextAlignment="Center" > 
         <TextBox.Text> 
          <Binding Path="Name" > 
           <Binding.ValidationRules> 
            <DataErrorValidationRule></DataErrorValidationRule> 
           </Binding.ValidationRules> 
          </Binding> 
         </TextBox.Text> 
        </TextBox> 

Xác thực hộp văn bản này là OK - Tôi có nghĩa là khung màu đỏ xuất hiện trên hộp văn bản nếu dữ liệu sai. Tuy nhiên những gì tôi cần làm là hiển thị chú giải công cụ trên hộp văn bản đó, nhưng điều quan trọng hơn là tôi phải tắt nút "Chạy" nếu bất kỳ hộp văn bản nào có dữ liệu sai. Cách tốt nhất để làm taht là gì ??

EDIT Vấn đề đầu tiên đã được giải quyết, nhưng tôi có một vấn đề khác. Tôi cần phải sử dụng MultiBindings để xác nhận nút của tôi. Vì vậy, tôi đã làm sth như thế

<Button x:Name="btnArrange" Grid.Column="0" Content="Rozmieść" Click="btnArrange_Click" > 
       <Button.Style> 
        <Style TargetType="Button"> 
         <Style.Triggers> 
          <DataTrigger Value="False"> 
           <DataTrigger.Binding> 
            <MultiBinding Converter="{StaticResource BindingConverter}"> 
             <Binding ElementName="txtName" Path="Validation.HasError" /> 
             <Binding ElementName="txtSurname" Path="Validation.HasError"/> 
             <Binding ElementName="txtAddress" Path="Validation.HasError"/> 

            </MultiBinding> 
           </DataTrigger.Binding> 
           <Setter Property="IsEnabled" Value="False"/> 

          </DataTrigger> 
         </Style.Triggers> 
        </Style>   
       </Button.Style> 

     </Button> 

My Chuyển đổi trông như thế

public class Converters : IMultiValueConverter 
{ 

    #region IMultiValueConverter Members 

    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
    { 
     if(values !=null && values.Length > 0) 
     { 


      if (values.Cast<type>().Count(val => val) > 0) 
       return false; 
      return true; 
     } 
     return false; 
    } 

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) 
    { 
     return null; 
    } 

    #endregion 
} 

Tuy nhiên tôi nhận được InvalidCastException trong chuyển đổi này. Một diễn viên thích hợp trong trường hợp đó là gì? Tôi thoght như thể HasError là một loại bool vì vậy tôi nên cast to bool.

+0

"Loại" có nghĩa là gì? Thay thế nó bằng "if (values.Cast (). Bất kỳ (val => val))" – vorrtex

Trả lời

2

Nếu bạn tạo tóm tắt xác thực, bạn có thể liên kết thuộc tính IsEnabled của nút "Chạy" với thuộc tính HasErrors.

Bạn sẽ cần sử dụng thuộc tính hoặc bộ chuyển đổi trung gian như bạn muốn IsEnabledtrue khi HasErrors là sai (và ngược lại).

+1

Làm cách nào để tạo tóm tắt xác thực? – stylus

+0

@validator - có một ở đây - http://codeblitz.wordpress.com/2009/05/12/wpf-validation-summary-control/ - Tôi đã nhầm lẫn với Silverlight, xin lỗi. – ChrisF

6
<Window.Resources> 
    <Style x:Key="ElementInError" TargetType="{x:Type FrameworkElement}"> 
     <Style.Triggers> 
      <Trigger Property="Validation.HasError" Value="True"> 
       <Setter Property="ToolTip" 
        Value="{Binding (Validation.Errors)[0].ErrorContent, RelativeSource={x:Static RelativeSource.Self}}"/> 
      </Trigger> 
     </Style.Triggers> 
    </Style> 
</Window.Resources> 
<!-- ... --> 
<TextBox x:Name="txtName" Style="{StaticResource ElementInError}"> 
    <!-- ... -->   
</TextBox> 
<!-- ... --> 
     <Button x:Name="OkButton" Content="Ok" Margin="5" Click="OkButton_Click"> 
      <Button.Style> 
       <Style TargetType="Button"> 
        <Style.Triggers> 
         <DataTrigger Binding="{Binding ElementName=txtName,Path=(Validation.HasError)}" Value="True"> 
          <Setter Property="IsEnabled" Value="False" /> 
         </DataTrigger> 
        </Style.Triggers> 
       </Style> 
      </Button.Style> 
     </Button> 
+0

Cảm ơn câu trả lời, Bạn có thể xem lại câu hỏi của tôi không - Tôi đã chỉnh sửa nó – stylus

17

Để hiển thị các thông báo lỗi trong một mẹo công cụ đặt này vào Application.Resources của bạn:

<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}"> 
    <Style.Triggers> 
    <Trigger Property="Validation.HasError" Value="true"> 
     <Setter Property="ToolTip" 
     Value="{Binding RelativeSource={x:Static RelativeSource.Self}, 
         Path=(Validation.Errors)[0].ErrorContent}"/> 
    </Trigger> 
    </Style.Triggers> 
</Style> 

(Ví dụ từ http://msdn.microsoft.com/en-us/library/system.windows.controls.validation.errortemplate.aspx)

Để bật/tắt một nút bạn có thể sử dụng một cái gì đó dọc theo dòng

<Button x:Name="btnOK" Content="OK" IsDefault="True" Click="btnOK_Click"> 
    <Button.Style> 
    <Style TargetType="{x:Type Button}"> 
     <Setter Property="IsEnabled" Value="false" /> 
     <Style.Triggers> 
     <MultiDataTrigger> 
      <MultiDataTrigger.Conditions> 
      <Condition Binding="{Binding ElementName=txt1, Path=(Validation.HasError)}" Value="false" /> 
      <Condition Binding="{Binding ElementName=txt2, Path=(Validation.HasError)}" Value="false" /> 
      </MultiDataTrigger.Conditions> 
      <Setter Property="IsEnabled" Value="true" /> 
     </MultiDataTrigger> 
     </Style.Triggers> 
    </Style> 
    </Button.Style> 
</Button> 

hoặc bạn có thể triển khai ICommand và sử dụng lệnh comm và ràng buộc.

EDIT

Dưới đây là một ví dụ làm việc đầy đủ. Nó hiển thị một cửa sổ với hai TextBox. Nút được bật nếu và chỉ khi cả hai Hộp văn bản đều không trống. Tạo một dự án có tên ValidationDemo và đưa các tập tin sau đây trong nó:

MainWindow.xaml:

<Window x:Class="ValidationDemo.MainWindow" 
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
     Title="MainWindow" Height="146" Width="223"> 
    <Window.Resources> 
    <Style TargetType="{x:Type TextBox}"> 
     <Style.Triggers> 
     <Trigger Property="Validation.HasError" Value="true"> 
      <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/> 
     </Trigger> 
     </Style.Triggers> 
    </Style> 
    </Window.Resources> 
    <Grid> 
    <Label Content="A" Height="28" HorizontalAlignment="Left" Margin="46,7,0,0" Name="label1" VerticalAlignment="Top" /> 
    <TextBox Name="txtA" Text="{Binding Path=TextA, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" Height="23" HorizontalAlignment="Left" Margin="69,12,0,0" VerticalAlignment="Top" Width="120" /> 
    <Label Content="B" Height="28" HorizontalAlignment="Left" Margin="46,39,0,0" Name="label2" VerticalAlignment="Top" /> 
    <TextBox Name="txtB" Text="{Binding Path=TextB, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True, ValidatesOnExceptions=True}" Height="23" HorizontalAlignment="Left" Margin="69,41,0,0" VerticalAlignment="Top" Width="120" /> 
    <Button Name="btnOk" Content="OK" Height="23" HorizontalAlignment="Left" Margin="114,70,0,0" VerticalAlignment="Top" Width="75" Click="btnOk_Click"> 
     <Button.Style> 
     <Style TargetType="{x:Type Button}"> 
      <Setter Property="IsEnabled" Value="false" /> 
      <Style.Triggers> 
      <MultiDataTrigger> 
       <MultiDataTrigger.Conditions> 
       <Condition Binding="{Binding ElementName=txtA, Path=(Validation.HasError)}" Value="false" /> 
       <Condition Binding="{Binding ElementName=txtB, Path=(Validation.HasError)}" Value="false" /> 
       </MultiDataTrigger.Conditions> 
       <Setter Property="IsEnabled" Value="true" /> 
      </MultiDataTrigger> 
      </Style.Triggers> 
     </Style> 
     </Button.Style> 
    </Button> 
    </Grid> 
</Window> 

MainWindow.xaml.cs:

using System.Windows; 

namespace ValidationDemo 
{ 
    /// <summary> 
    /// Interaction logic for MainWindow.xaml 
    /// </summary> 
    public partial class MainWindow : Window 
    { 

    private Model model = new Model(); 

    public MainWindow() 
    { 
     InitializeComponent(); 
     this.DataContext = this.model; 
    } 

    private void btnOk_Click(object sender, RoutedEventArgs e) 
    { 
     Application.Current.Shutdown(); 
    } 
    } 
} 

Model.cs:

using System; 
using System.ComponentModel; 

namespace ValidationDemo 
{ 
    public class Model : INotifyPropertyChanged, IDataErrorInfo 
    { 
    public event PropertyChangedEventHandler PropertyChanged; 

    private string textA = string.Empty; 
    public string TextA 
    { 
     get 
     { 
     return this.textA; 
     } 
     set 
     { 
     if (this.textA != value) 
     { 
      this.textA = value; 
      this.OnPropertyChanged("TextA"); 
     } 
     } 
    } 

    private string textB = string.Empty; 
    public string TextB 
    { 
     get 
     { 
     return this.textB; 
     } 
     set 
     { 
     if (this.textB != value) 
     { 
      this.textB = value; 
      this.OnPropertyChanged("TextB"); 
     } 
     } 
    } 

    public string Error 
    { 
     get { throw new NotImplementedException(); } 
    } 

    public string this[string columnName] 
    { 
     get 
     { 
     string result = string.Empty; 
     switch (columnName) 
     { 
      case "TextA": 
      if (string.IsNullOrEmpty(this.textA)) 
      { 
       result = "'A' must not be empty"; 
      } 
      break; 
      case "TextB": 
      if (string.IsNullOrEmpty(this.textA)) 
      { 
       result = "'B' must not be empty"; 
      } 
      break; 
     } 
     return result; 
     } 
    } 

    protected virtual void OnPropertyChanged(string propertyName) 
    { 
     if (this.PropertyChanged != null) 
     { 
     this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 

    } 

} 
+0

Unfortunatelly nó không hoạt động. Mặc dù một trong những xác nhận của hộp văn bản của tôi không thành công nút Ok của tôi vẫn được kích hoạt – stylus

+0

@validator: Tôi đã thêm một ví dụ làm việc. – TomBot

Các vấn đề liên quan