依赖属性不更新

时间:2013-11-08 09:33:04

标签: c# wpf binding dependency-properties updating

我正在尝试将参数添加到自定义验证规则中。为此我定义了一个依赖对象:

public class SettingsValueValidationDependencyObject : DependencyObject
{
    public Custom.ValueType ValueTypeForValidation
    {
        get { return (Custom.ValueType)this.GetValue(ValueTypeForValidationProperty); }
        set { this.SetValue(ValueTypeForValidationProperty, value); }
    }

    public static readonly DependencyProperty ValueTypeForValidationProperty = DependencyProperty.Register("ValueTypeForValidation", typeof(Custom.ValueType), typeof(SettingsValueValidationDependencyObject), new UIPropertyMetadata(Custom.ValueType.Int32Value));
}

我的验证规则类如下所示:

public class SettingsValueValidationRule : ValidationRule
{
    public SettingsValueValidationDependencyObject SettingsValueValidationDependencyObject
    {
        get;
        set;
    }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        // validation...
    }
}

xaml代码:

<DataGridTextColumn Header="Value" Width="150">
    <DataGridTextColumn.Binding>
        <Binding Path="Value">
            <Binding.ValidationRules>
                <validators:SettingsValueValidationRule>
                    <validators:SettingsValueValidationRule.SettingsValueValidationDependencyObject>
                        <validators:SettingsValueValidationDependencyObject ValueTypeForValidation="{Binding ValueType}"/>
                    </validators:SettingsValueValidationRule.SettingsValueValidationDependencyObject>
                </validators:SettingsValueValidationRule>
            </Binding.ValidationRules>
        </Binding>
    </DataGridTextColumn.Binding>
</DataGridTextColumn>

两个属性Value和ValueType都属于同一个对象,DataGrid的ItemsSource绑定到这些对象的列表。当我编辑Value单元格时,ValueTypeForValidation属性始终是默认值(我还有一列用于显示ValueType及其绝对的另一个值)。我还尝试在Validate方法中手动更新BindingExpression但它不起作用。我做错了什么?

1 个答案:

答案 0 :(得分:0)

ValidationRules中没有绑定。

ValidationRules不是LogicalTree的一部分,因此在Binding中没有DataContext作为Source。

互联网上有一些技巧,如何使ValidationRule“可绑定”。

看看这个啧啧:

Binding on a Non-UIElement