私のビューには、次のような TextBox があります。
<TextBox x:Name="tBoxShippingWeight" Text="{Binding ShippingWeight, Mode=TwoWay}" InputScope="Number" />
ユーザーが値を入力すると、基本的な検証を行います (この質問の焦点ではありません)。それが失敗した場合は、System.Windows.MessageBox を使用してユーザーに適切なパラメーターを通知し、値を以前の値に戻します。デフォルトの init 値から取得されたか、ユーザーが適切に入力したため、常に有効です。検証を行う if ステートメント内で RaisePropertyChanged("ShippingWeight") を呼び出すことになりました。それを catch ステートメントに入れると、MessageBox もそこから呼び出された場合に発生することはありません。これは復帰を行うための合理的な方法ですか、それとももっと良い方法がありますか? ViewModel のコードは次のとおりです。
public string ShippingWeight
{
get { return ShippingModel.ShippingWeight.ToString(); }
set
{
if (ShippingModel.ShippingWeight.ToString() == value) return;
var oldValue = ShippingModel.ShippingWeight;
try
{
int intValue = Convert.ToInt32(value);
if (Convert.ToInt32(ShippingParams.ShippingWeightMin) > intValue || Convert.ToInt32(ShippingParams.ShippingWeightMax) < intValue)
{
// Revert back to previous value
// NOTE: This has to be done here. If done in the catch statement,
// it will never run since the MessageBox interferes with it.
RaisePropertyChanged("ShippingWeight");
throw new Exception();
}
ShippingModel.ShippingWeight = intValue;
RaisePropertyChanged("ShippingWeight", oldValue, Convert.ToDouble(value), true);
}
catch (Exception)
{
System.Windows.MessageBox.Show("Value must be a whole number between " + ShippingParams.ShippingWeightMin + " and " + ShippingParams.ShippingWeightMax);
}
}
}