当ValidationRule失败时,属性绑定不会更新

Nig*_*mes 5 c# wpf xaml validationrules

我在输入字段中有几个TextBox,在我的视图中有一个"Save"按钮.其中两个TextBox是保存所必需的字段,我在xaml中设置了一个自定义ValidationRule,用于一些视觉反馈(红色边框和工具提示),如下所示:

<TextBox ToolTip="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}">
    <TextBox.Text>
        <Binding Path="ScriptFileMap" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <v:MinimumStringLengthRule MinimumLength="1" ErrorMessage="Map is required for saving." />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>
Run Code Online (Sandbox Code Playgroud)

"保存"按钮链接到一个调用SaveScript()函数的DelegateCommand.如果两个必填字段的属性为空,则该函数不允许用户保存:

public void SaveScript()
{
    if (this.ScriptFileName.Length > 0 && this.ScriptFileMap.Length > 0)
    {
        // save function logic
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,该功能仍允许保存文件.仔细观察,我发现当ValidationRule失败时,这两个字段(ScriptFileName和ScriptFileMap)的值没有被更新,并且它超过了最后的已知值.

这是ValidationRule的预期行为还是我在某处丢失了某些东西或出现故障?如果是前者,有没有办法覆盖这种行为?如果空字符串永远不会传递给bound属性,我无法阻止ViewModel中的保存.

Mik*_*bel 8

是的,这是预期的行为.默认情况下,验证规则在原始建议值上运行,即转换之前的值并将其写回绑定源.

尝试将ValidationStep规则更改为UpdatedValue.这应该强制规则在转换和写回新值后运行.


Nig*_*mes 1

由于我从未让 ValidationRule 正常工作,因此我采取了不同的方法,只使用了一些绑定。这是我的文本框,其中包含文本、边框和工具提示的绑定:

<TextBox Text="{Binding Path=ScriptFileName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" BorderBrush="{Binding Path=ScriptFileNameBorder, UpdateSourceTrigger=PropertyChanged}" ToolTip="{Binding Path=ScriptFileNameToolTip, UpdateSourceTrigger=PropertyChanged}" />
Run Code Online (Sandbox Code Playgroud)

这是我对文本字段的绑定,其中包含自己更新边框和工具提示的逻辑(无需验证):

public string ScriptFileName
        {
            get
            {
                return this.scriptFileName;
            }

            set
            {
                this.scriptFileName = value;
                RaisePropertyChanged(() => ScriptFileName);

                if (this.ScriptFileName.Length > 0)
                {
                    this.ScriptFileNameBorder = borderBrushNormal;
                    this.scriptFileNameToolTip.Content = "Enter the name of the file.";
                }
                else
                {
                    this.ScriptFileNameBorder = Brushes.Red;
                    this.scriptFileNameToolTip.Content = "File name is required for saving.";
                }
            }
        }
Run Code Online (Sandbox Code Playgroud)

通过这种方式,当该框留空时,我可以获得所需的用户反馈(红色边框和工具提示消息),并且仍然使用 SaveScript 函数中的代码来防止“保存”按钮工作。

这需要更多的输入,因为我需要为每个我想要的附加字段设置单独的属性,但我尝试过的所有其他内容要么没有效果,要么破坏了程序中的其他内容(包括 ValidationRules 和 DataTriggers)。