在绑定到数据源的ItemsControl
内,我尝试使用自定义验证规则验证TextBox
,该规则接受参数,以下是vaildation规则的代码。 / p>
public class RatioValidation : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
if (!String.IsNullOrEmpty(Maturity.MaturityValue) && Helper.IsDateInCorrectFormat(Maturity.MaturityValue))
{
String strVal = Convert.ToString(value);
Double ratio = 0;
Boolean isValid = Double.TryParse(strVal, out ratio);
if (isValid)
{
if (ratio <= 0)
return new ValidationResult(false, "Please enter a valid ratio!");
else return new ValidationResult(true, null);
}
return new ValidationResult(false, "Please enter a valid ratio!");
}
else return new ValidationResult(true, null);
}
private MaturityDependencyForValidation _maturity;
public MaturityDependencyForValidation Maturity
{
get { return _maturity; }
set { _maturity = value; }
}
}
public class MaturityDependencyForValidation : DependencyObject
{
public String MaturityValue
{
get { return (String)GetValue(MaturityValueProperty); }
set { SetValue(MaturityValueProperty, value); }
}
public static readonly DependencyProperty MaturityValueProperty =
DependencyProperty.Register("MaturityValue", typeof(String), typeof(MaturityDependencyForValidation), new UIPropertyMetadata(null));
}
然后像下面一样使用它,
<TextBox Grid.Row="1" Grid.Column="2" Name="txtRatio" BorderThickness="0" Width="148" Tag="{Binding StrMaturity, UpdateSourceTrigger=PropertyChanged}">
<TextBox.Text>
<Binding Path="Ratio" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<leg:RatioValidation ValidatesOnTargetUpdated="True">
<leg:RatioValidation.Maturity>
<leg:MaturityDependencyForValidation MaturityValue="{Binding txtMaturity}"/>
</leg:RatioValidation.Maturity>
</leg:RatioValidation>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
我在输出窗口中出现异常:
无法为目标元素找到管理FrameworkElement或FrameworkContentElement。 BindingExpression:路径= txtMaturity;的DataItem = NULL; target元素是'MaturityDependencyForValidation'(HashCode = 63478077); target属性是'Maturity'(类型'String')
在RatioValidation
规则中,Maturity
的值永远不会受到数据绑定的约束。我需要这个数据绑定值。请帮忙。
答案 0 :(得分:1)
周围的对象没有DataContext
,至少绑定不是DependencyObjects
,你的选择有点受限,它应该与{{3}时的情况相似},另见binding in an array。