2017-01-10 10 views
0

私は次のXAMLを持っている:WPFのValidationRule滴下小数点

  <TextBox Name="LevyWageLimitFormulaID_TextBox" 
        Width="150" 
        HorizontalAlignment="Center" 
        Grid.Row="4" Grid.Column="1"> 
       <TextBox.Text> 
        <Binding Path="SelectedStateRule.LevyRule.WageLimitFormulaID" 
          UpdateSourceTrigger="PropertyChanged"> 
         <Binding.ValidationRules> 
          <vm:NumericValidator ValidatesOnTargetUpdated="True" /> 
         </Binding.ValidationRules> 
        </Binding> 
       </TextBox.Text> 
      </TextBox> 

バリデータは、このような次のように定義されます私は小数点数を入力しようとするまで

/// <summary> 
/// Numeric Validator to make sure value is numeric 
/// </summary> 
public class NumericValidator : ValidationRule 
{ 
    /// <summary> 
    /// Validate field is blank or contains only numbers 
    /// </summary> 
    /// <param name="value"></param> 
    /// <param name="cultureInfo"></param> 
    /// <returns></returns> 
    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) 
    { 
     Decimal _number; 
     if (!Decimal.TryParse((value as string), out _number) && !String.IsNullOrEmpty(value as string)) 
     { 
      return new ValidationResult(false, "Value must be numeric"); 
     } 

     return ValidationResult.ValidResult; 
    } 
} 

これが正常に動作します。テキストボックスに'10.'と入力すると、小数点が削除されます(ユーザーは、小数点がテキストボックスに表示されることはありません)。 '100'と入力してカーソルを手動で移動し、小数点を追加して'10.0'の値を有効にし、小数点が残るようにします。

これは、Decimal.TryParseout _number部分が、プロパティが変更されるとすぐに検証が実行されることに起因することがわかりましたが(これは要件の1つです)、このメソッドを修正する方法があります。入力することができます'10.'小数点は、テキストボックスに残りますか?

答えて

1

これはValidationRuleが原因ではありません。一時的にValidationRuleを削除すると、同じ動作が発生します。

問題がdecimalソースプロパティdecimal値と「10」以外の何かに設定することができないということです実際には有効なdecimal値ではありません。あなたは何ができるか

decimalプロパティを設定するラッパーstringプロパティにバインドすることです:

//add this wrapper property to your class: 
private string _wrapper; 
public string Wrapper 
{ 
    get { return _wrapper; } 
    set 
    { 
     _wrapper = value; 
     decimal d; 
     if (Decimal.TryParse(_wrapper, out d)) 
      WageLimitFormulaID = d; 
    } 
} 

private decimal _wageLimitFormulaID; 
public decimal WageLimitFormulaID 
{ 
    get { return _wageLimitFormulaID; } 
    set { _wageLimitFormulaID = value; } 
} 

<TextBox Name="LevyWageLimitFormulaID_TextBox" 
        Width="150" 
        HorizontalAlignment="Center" 
        Grid.Row="4" Grid.Column="1"> 
    <TextBox.Text> 
     <Binding Path="SelectedStateRule.LevyRule.Wrapper" UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <vm:NumericValidator ValidatesOnTargetUpdated="True" /> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 
+0

はい、あなたは正しいです。しかし、一般に、このアプローチはそれほど有用ではありません。すべてのプロパティのラッパーを追加する必要があります。私はそれが十進数のテキストボックスコントロールを見つけて、十進数の値にバインドする必要があるどこでもそれを使用することをお勧めしますね。 –

+0

唯一の違いは、「このアプローチ」がコントロールに実装されることです。ここでも小数点以下のプロパティに10進数のプロパティを設定することはできません。 – mm8

関連する問題