2013-08-28 70 views
0

我使用WPF MVVM IM我的项目之一。我有一个我绑定到对象列表的数据网格。处理错误

<DataGrid ItemsSource="{Binding Path=ListOfValues}" Margin="5,38" 

在我的视图模型类我有ListOfValues

public ObservableCollection<ClassA> ListOfValues 
     { 
      get { return listOfValues; } 
      set 
      { 
       listOfValues= value; 
       RaisePropertyChangedEvent("ListOfValues"); 
      } 
     } 

在我的ClassA的财产,我有三个特性。

public string Name { get; set; } 
public long No { get; set; }   
public decimal Amount { get; set; } 

在网格中,用户只能输入Amount字段的值。我想验证用户是否输入该字段的有效十进制值。

推荐我一个地方,我能赶上execption。我试图在窗口关闭时处理它。但是如果用户输入了无效值,那么它没有保存在视图的数据上下文中。此外,我试图验证它的ClassA中的二传手它没有击中值的制定者。

+0

你如何做验证?你使用IDataErrorInfo接口? – sevdalone

+0

不,我不是使用IDataErrorInfo – udaya726

+0

我建议你为你ClassA实现IDataErrorInfo接口和INotifyPropertyChanged接口。 – sevdalone

回答

0

也许你可以从不同的角度攻击这个问题...怎么样进入任何非数字字符到停止用户TextBox在第一位?

为此,您可以使用PreviewTextInputPreviewKeyDown事件......有关附加处理程序的TextBox和这段代码添加到他们:如果你想采取重一点时间

public void TextCompositionEventHandler(object sender, TextCompositionEventArgs e) 
{ 
    // if the last pressed key is not a number or a full stop, ignore it 
    return e.Handled = !e.Text.All(c => Char.IsNumber(c) || c == '.'); 
} 

public void PreviewKeyDownEventHandler(object sender, KeyEventArgs e) 
{ 
    // if the last pressed key is a space, ignore it 
    return e.Handled = e.Key == Key.Space; 
} 

可用性,你可以把它放到一个Attached Property ...这是很好能够添加此功能的属性:

<TextBox Text="{Binding Price}" Attached:TextBoxProperties.IsDecimalOnly="True" /> 
+0

嗨,它是一个数据网格中的一个列而不是一个文本框 – udaya726

+0

“文本框”只是显示了如何在包装在“附加属性”中时使用此功能。但是,您可以添加一个'DataGridTemplateColumn',为其定义一个'DataTemplate'并在其中包含'TextBox'并将这些处理程序附加到该'TextBox'。有关详细信息,请参阅MSDN中的[DataGridTemplateColumn类](http://msdn.microsoft.com/zh-cn/library/system.windows.controls.datagridtemplatecolumn.aspx)页面。 – Sheridan

+0

我已经使用PreviewTextInput操作来限制输入。谢谢 – udaya726

0

我强烈建议你实现你的数据类型的类IDataErrorInfo接口。你可以找到它here一个完整的教程,但基本而言,这是它如何工作的。

我们需要一个indexer添加到每个班级:

public string this[string columnName] 
{ 
    get 
    { 
     string result = null; 
     if (columnName == "FirstName") 
     { 
      if (string.IsNullOrEmpty(FirstName)) 
       result = "Please enter a First Name"; 
     } 
     if (columnName == "LastName") 
     { 
      if (string.IsNullOrEmpty(LastName)) 
       result = "Please enter a Last Name"; 
     } 
     return result; 
    } 
} 

从链接教程

采取了这种indexer,我们增加我们的验证要求依次每个属性。您可以添加多重要求每个属性:

 if (columnName == "FirstName") 
     { 
      if (string.IsNullOrEmpty(FirstName)) result = "Please enter a First Name"; 
      else if (FirstName.Length < 3) result = "That name is too short my friend"; 
     } 

无论你在result参数返回作为UI中的错误消息。为了这个工作,你需要添加到您的binding值:

Text="{Binding FirstName, ValidatesOnDataErrors=true, NotifyOnValidationError=true}" 
+0

谢谢谢里登。如果列类型是字符串,你的代码对我来说很好。但是对于小数列,它只显示红色边框。 – udaya726