0

私は自分のプロジェクトの 1 つに WPF MVVM を使用しています。オブジェクトのリストにバインドするデータグリッドがあります。

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

私のビュー モデル クラスには、ListOfValues のプロパティがあります。

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

私の ClassA には、3 つのプロパティがあります。

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

グリッドでは、ユーザーは金額フィールドの値のみを入力できます。ユーザーがそのフィールドに有効な小数値を入力したかどうかを検証したいと思います。

例外をキャッチできる場所を教えてください。私は窓の近くでそれを処理しようとします。ただし、ユーザーが無効な値を入力すると、ビューのデータ コンテキストに保存されません。また、ClassAのセッターで値のセッターにヒットしないことを検証しようとしました。

4

2 に答える 2

0

おそらく、別の角度からこの問題に取り組むことができます...TextBox最初に、ユーザーが数値以外の文字を に入力しないようにするのはどうですか?

PreviewTextInputおよびイベントを使用してこれを行うことができPreviewKeyDownます...問題のハンドラーにハンドラーを添付し、次の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" />
于 2013-08-29T08:28:10.833 に答える
0

IDataErrorInfoデータ型クラスにインターフェイスを実装することを強くお勧めします。ここで完全なチュートリアルを見つけることができますが、基本的には、これがどのように機能するかです.

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}" 
于 2013-08-28T11:48:03.377 に答える