我在涉足 WPF 并注意到一个我以前从未见过的特性。在下面的示例中,我有两个文本框绑定(bind)到代码隐藏中的同一个 DP。
代码隐藏:
public partial class MainWindow : Window
{
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(Window), new FrameworkPropertyMetadata("Hello"));
public MainWindow()
{
InitializeComponent();
}
}
XAML:
<TextBox>
<TextBox.Text>
<Binding RelativeSource = "{RelativeSource Mode=FindAncestor, AncestorType=Window}" Path="Text" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay">
<Binding.ValidationRules>
<utils:RestrictInputValidator Restriction="IntegersOnly" ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
<TextBox Name="TextBox" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}, Mode=TwoWay, Path=Text, UpdateSourceTrigger=PropertyChanged}"/>
我注意到,当我在包含 IntegerOnly 验证但未通过验证的 TextBox 中键入内容时(在本例中为非整数的任何内容),基础 Text 变量不会更新。 这是默认行为吗?为什么要这样做?是否可以覆盖?
最佳答案
将 ValidationRule 的 ValidationStep 设置为 CommitedValue,这将在值提交到源 (msdn) 后运行验证。
<utils:RestrictInputValidator Restriction="IntegersOnly" ValidationStep="CommitedValue" ValidatesOnTargetUpdated="True"/>
编辑: 将 validationstep 设置为 CommitedValue 或 UpdatedValue 时,BindingExpression 将发送到 Validate 方法,而不是实际值。我不知道是否有另一种方法来获取 BindingExpression 的值,但我制作了一个扩展方法来获取它:
public static class BindingExtensions
{
public static T Evaluate<T>(this BindingExpression bindingExpr)
{
Type resolvedType = bindingExpr.ResolvedSource.GetType();
PropertyInfo prop = resolvedType.GetProperty(
bindingExpr.ResolvedSourcePropertyName);
return (T)prop.GetValue(bindingExpr.ResolvedSource);
}
}
关于c# - 导致绑定(bind)不更新的验证错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17602579/