IDataErrorInfo 与 MVVM Light 消息传递一起重新附加

本文关键字:一起 新附加 消息传递 Light MVVM IDataErrorInfo | 更新日期: 2023-09-27 17:55:16

对于我正在处理的项目,我使用 IDataErrorInfo 来验证用户输入。我也在使用 MVVM 轻量级消息传递。但似乎错误处理在每个 ShowDialog 上都会重新附加,这会导致验证多次发生,并且每次显示对话框时都会堆叠起来。视图模型在打开/关闭期间保留,不会重新创建。

视图(文本框)

<TextBox Name="LPNInput" Grid.Column="1" VerticalAlignment="Center"
         HorizontalAlignment="Stretch" Margin="10,40,10,10"
         Text="{Binding Path=LPN, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"
         extensions:FocusExtension.IsFocused="True">
  <TextBox.Style>
    <Style BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type TextBox}">
      <Setter Property="Validation.ErrorTemplate" Value="{StaticResource LpnValidationErrorTemplate}" />
   </Style>
 </TextBox.Style>
 <TextBox.InputBindings>
   <KeyBinding Command="{Binding Path=SubmitLPNCommand}" Key="Enter" />
 </TextBox.InputBindings>   
</TextBox>
视图模型

请求输入视图模型

private string lpn;
public string LPN
{
    get { return lpn; }
    set
    {
        lpn = value; RaisePropertyChanged("LPN");
    }
}
public string Error { get; private set; }
public string this[string propertyName]
{
    get
    {
        string errorMsg = string.Empty;
        if (propertyName.Equals("LPN"))
        {
            pannenkoek++;
            if (!string.IsNullOrEmpty(lpn))
            {
                if (!LicensePlateNumber.IsValidLPN(lpn))
                {
                    errorMsg = XmlTextProvider.GetHeader("LPNInvalid");
                }
                else if (!someManager.CanAddBag(LicensePlateNumber.Parse(lpn)))
                {
                    errorMsg = XmlTextProvider.GetHeader("LPNDuplicate");
                }
            }
        }
        Error = errorMsg;
        return Error;
    }
}
private void Close(bool dialogResult)
{
    System.Diagnostics.Debug.WriteLine(string.Format("Pannenkoeken: {0}", pannenkoek));
    // Notify the view to close the dialog
    Messenger.Default.Send<CloseWindowMessage, RequestInputDialog>(new CloseWindowMessage(this, dialogResult));
}

视图模型 #2

RequestLPNViewModel 是在视图模型 #2 的构造函数中创建的。

Application.Current.Dispatcher.BeginInvoke(new Action(() => Messenger.Default.Send<ShowDialogMessageBase, MainView>(new ShowDialogMessage<RequestInputDialog>(this, RequestInputViewModel, InputEntered))));

调试输出中的输出

Pannenkoeken: 2Pannenkoeken: 4Pannenkoeken: 6Pannenkoeken: 8

我不希望人数增加。我本来期望数字 2 的 4 倍。似乎错误绑定在创建对话框时附加,但在关闭对话框时未释放。是的,int 在打开:)时重置

IDataErrorInfo 与 MVVM Light 消息传递一起重新附加

由于对话框行为,我选择在每次创建对话框时重新创建视图模型。也许最好这样做,以防止将来使用旧/以前的数据出现任何"奇怪"行为。

视图模型不会以这种方式表示任何状态。