6

我的视图中有一些用于输入字段的文本框和一个“保存”按钮。其中两个 TextBoxes 是保存的必填字段,我在 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>

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

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

但是,该功能仍然允许保存文件。仔细检查后,我发现当 ValidationRule 失败时,这两个字段(ScriptFileName 和 ScriptFileMap)的值没有被更新,它是最后一个已知值。

这是 ValidationRule 的预期行为,还是我缺少某些东西或某处出现故障?如果是前者,有没有办法覆盖这种行为?如果从未将空字符串传递到绑定属性,我无法阻止在 ViewModel 中保存。

4

3 回答 3

8

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

尝试将ValidationStepon 您的规则更改为UpdatedValue. 这应该强制规则在新值被转换并写回后运行。

于 2014-10-22T17:31:03.673 回答
2

您应该实现CanExecute方法和RaiseCanExecuteChanged事件,这将使您的按钮保持禁用状态,直到所有必需的属性都通过验证逻辑。

于 2014-10-23T17:27:08.293 回答
1

因为我从来没有让 ValidationRule 正常工作,所以我采用了不同的方法,只是使用了一些绑定。这是我的文本框,带有文本、边框和工具提示的绑定:

<TextBox Text="{Binding Path=ScriptFileName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" BorderBrush="{Binding Path=ScriptFileNameBorder, UpdateSourceTrigger=PropertyChanged}" ToolTip="{Binding Path=ScriptFileNameToolTip, UpdateSourceTrigger=PropertyChanged}" />

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

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.";
                }
            }
        }

这样做可以让我在框为空时获得我想要的用户反馈(红色边框和工具提示消息),并且仍然使用我的 SaveScript 函数中的代码来阻止“保存”按钮工作。

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

于 2014-10-23T17:09:17.497 回答