0

小数プロパティを検証するためのカスタム検証属性があります

public sealed class DecimalAttribute : ValidationAttribute
{
    public DecimalAttribute()
    {
        this.ErrorMessage = "The input must be a decimal number";
    }

    private object Value { get; set; }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        this.Value = value;

        return base.IsValid(value, validationContext);
    }

    public override bool IsValid(object value)
    {
        if (this.Value == null) return false;

        decimal result;
        return decimal.TryParse(this.Value.ToString(), out result);
    }
}

ただし、それが機能せず、テキストボックスをそのプロパティにバインドしてテキストボックスに無効な値を入力すると、カスタム検証属性のエラーメッセージの代わりに「値 '' を変換できませんでした」というメッセージが表示されます。

興味深いことに、"Required" などの他の検証属性は数値プロパティでも機能しないことがわかりました。

編集

私のバインド部分は次のとおりです。

    <TextBox>
        <TextBox.Text>
            <Binding Path="Price" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" NotifyOnValidationError="True">
                <Binding.ValidationRules>
                    <local:DecimalValidationRule />
                </Binding.ValidationRules>
            </Binding>
        </TextBox.Text>
    </TextBox>

私の解決策

これが私の問題を解決した方法です。それが最善の方法かどうかはわかりませんが、あなたの推奨事項について共有します。

私は実際に 2 つのプロパティを使用しました。1 つはバインディングと検証用、もう 1 つはデータベースにデータを保存するためです。

    [NotMapped, Decimal]
    public string PriceString
    {
        get { return _priceString; }
        set { if (SetValue(ref _priceString, value)) OnPropertyChanged("Price"); }
    }

    public decimal Price
    {
        get
        {
            decimal result;
            decimal.TryParse(this.PriceString, out result);
            return result;
        }
        set { PriceString = value.ToString(); }
    }

今、それは私が必要としているものとまったく同じです。

あなたのコメントをして、あなたの提案をして、より良い解決策を提供してください.

4

2 に答える 2

0

クラス宣言の上に [AttributeUsage(AttributeTargets.Property)] を追加します。

[AttributeUsage(AttributeTargets.Property)] 
public sealed class DecimalAttribute : ValidationAttribute
于 2015-09-01T08:02:49.747 に答える
0

プロパティに ValidationAttribute を追加する必要があります

[DecimalAttribute] // <-- this part is missing
public decimal Price
    {
       // get set
    }

また、必要な場合があります

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
于 2015-09-01T12:02:12.323 に答える