2011-02-08 104 views
0

我有一個wpf-mvvm應用程序。我們可以在驗證時設置源對象的屬性嗎?

在下面的代碼中,「PartBPremiumBuydown」是一個類的實例。其中有兩個屬性=> 1.值。和2. HasValidationError。

屬性「值」用於綁定到文本框。如果有任何驗證錯誤...我可以設置HasValidationError = true?

<TextBox ToolTip="{Binding RelativeSource={RelativeSource Self}, 
         Path=(Validation.Errors).CurrentItem.ErrorContent}"> 
         <TextBox.Text> 
          <Binding Path="PartBPremiumBuydown.Value" 
             ValidatesOnDataErrors="True" 
             UpdateSourceTrigger="PropertyChanged" 
          Converter="{x:Static localns:Converters.DecimalToCurrency}"> 
           <Binding.ValidationRules> 
            <localns:CurrencyRule /> 
           </Binding.ValidationRules> 
          </Binding> 
         </TextBox.Text> 
        </TextBox> 

回答

1

你應該有PartBPremiumBuydown實現IDataErrorInfo界面,類似下面的代碼:

public string Error { get; private set; } 
public string this[string propertyName] 
{ 
    get 
    { 
     string mError = string.Empty; 
     if (propertyName == "Value" 
      && !<insert your rule>) 
     { 
      mError = "Validation error text." 
     } 
     Error = mError; 
     return (string.IsNullOrWhiteSpace(mError))// if NOTHING 
      ? null        // then return null 
      : mError;        // else return error 
    } 
} 

現在,當您在文本框綁定到Value,如果用戶在打破你的規則文本輸入,驗證錯誤將顯示在TextBox上。

+0

請參閱[使用WPF強制執行複雜業務數據規則](http://msdn.microsoft.com/zh-cn/magazine/ff714593.aspx) – 2011-02-08 18:44:04

相關問題