ValidationRule with ValidationStep=“UpdatedValue” is called with BindingExpression instead of updated value

前端 未结 4 963
小鲜肉
小鲜肉 2020-12-03 01:06

I am getting started with using ValidationRules in my WPF application, but quite confused.

I have the following simple rule:

class RequiredRule : Val         


        
4条回答
  •  悲&欢浪女
    2020-12-03 01:57

    This is an extension to mbmcavoy's answer.

    I have modified the GetBoundValue method in order to remove the limitation for binding paths. The BindingExpression conveniently has the properties ResolvedSource and ResolvedSourcePropertyName, which are visible in the Debugger but not accessible via normal code. To get them via reflection is no problem though and this solution should work with any binding path.

    private object GetBoundValue(object value)
    {
        if (value is BindingExpression)
        {
            // ValidationStep was UpdatedValue or CommittedValue (validate after setting)
            // Need to pull the value out of the BindingExpression.
            BindingExpression binding = (BindingExpression)value;
    
            // Get the bound object and name of the property
            string resolvedPropertyName = binding.GetType().GetProperty("ResolvedSourcePropertyName", BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance).GetValue(binding, null).ToString();
            object resolvedSource = binding.GetType().GetProperty("ResolvedSource", BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance).GetValue(binding, null);
    
            // Extract the value of the property
            object propertyValue = resolvedSource.GetType().GetProperty(resolvedPropertyName).GetValue(resolvedSource, null);
    
            return propertyValue;
        }
        else
        {
            return value;
        }
    }
    

提交回复
热议问题