对话框中的 MaterialDesignInXaml 验证 - 如何比较 2 个文本框?

MaterialDesignInXaml validation in dialogs - how to compare 2 textboxes?

我正在尝试使用 MVVM 模式(、eactiveUI 和 MaterialDesignInXaml)编写简单的 WPF 应用程序。 在主 window 上,我有带有 2 个文本框的 DialogHost,然后是取消和保存按钮。 该对话框存储为资源,并通过传递 EmployeeViewModel 视图模型从主 window 视图模型打开。 该视图模型仅包含 2 个属性:EmployeeSurname 和 EmployeeName(不像我所知道的真正的视图模型,但它用于对话主机并从中获取数据)。 我在单独的 class 中也有简单的验证规则(此处未包含),我目前通过 xaml 添加到我的一个文本框。 基本的东西验证在单个元素上工作得很好,但我想实现更多,特别是:

  1. 如何比较2个或更多复选框?我无法将数据从另一个文本框传递到验证规则,它仅适用于分配规则的当前文本框。
  2. 如何在现有对话框之上显示另一个对话框(即在关闭对话框之前要求确认以保存更改)- 这是正确的方法吗?
  3. 如何在打开对话框时禁用保存按钮(以便在用户第一次输入正确值时启用)? 那个看起来很简单,我可以很容易地使用 main window 上的命令来执行此操作,但是使用 MaterialDesignInXaml 对话框按钮中使用的路由命令,我不确定如何实现此操作

XAML

     <DataTemplate DataType="{x:Type local:EmployeeViewModel}">

TextBox1:

                <TextBox Name="txtEmployeeName" MaxLength="8">
                <TextBox.Text>
                    <Binding Path="EmployeeName" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <VR:NameSurnameRule/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>

TextBox2(还没有任何验证):

<TextBox Name="txtSurname" Text="{Binding EmployeeSurname, UpdateSourceTrigger=PropertyChanged}" />

保存按钮:

            <Button Content="_Login" Command="{x:Static md:DialogHost.CloseDialogCommand}" Grid.Row="1" Grid.Column="2">
            <Button.CommandParameter> 
                <system:Boolean>True</system:Boolean>
            </Button.CommandParameter>
            <Button.Style>
                <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding Path=(Validation.HasError), ElementName=txtEmployeeName}" Value="True">
                            <Setter Property="IsEnabled" Value="False" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

取消按钮

<Button Content="_Cancel" Command="{x:Static md:DialogHost.CloseDialogCommand}" Grid.Row="1" Grid.Column="0" />

该对话框在资源中,没有代码隐藏。 提前致谢

您可以使用包装器方法将某些内容传递给验证规则,很好的例子是 here。或者您可以在您的模型中使用 IErrorDataInfo 进行验证(或将此方法与规则验证结合使用,但在您的视图模型中附加规则)。 对于第一次验证,您可以在 ViewModel 构造函数中引发 PropertyChanged,它会强制进行第一次验证。

谢谢,那个包装器起作用了,但在测试了一些其他东西之后,我最终决定使用 https://fluentvalidation.net/ 。在那里比较字符串非常容易,我发现它非常灵活。 关于初始验证,我发现只需将 ValidatesOnTargetUpdated="True" 添加到 xaml 中的验证规则就可以了(当我使用流利验证时不需要):

    <TextBox.Text>
<Binding Path="EmployeePassword2" UpdateSourceTrigger="PropertyChanged">
                                    <Binding.ValidationRules>
                                        <VR:NameSurnameRule ValidatesOnTargetUpdated="True"/>
                                    </Binding.ValidationRules>
                                </Binding>
                            </TextBox.Text>