WPF绑定ValidationRule中的属性

5

我需要一个包含两个文本框的表单:

  1. TotalLoginsTextBox

  2. UploadsLoginsTextBox

我想限制 UploadsLoginsTextBox 的输入,使其最大值为 TotalLoginsTextBox 的值。我还使用了一个值转换器,所以我尝试将 Maximum 值绑定:

以下是 XAML 代码:

<!-- Total Logins -->
<Label Margin="5">Total:</Label>
<TextBox Name="TotalLoginsTextBox" MinWidth="30" Text="{Binding Path=MaxLogins, Mode=TwoWay}" />
<!-- Uploads -->
<Label Margin="5">Uploads:</Label>
<TextBox Name="UploadsLoginsTextBox" MinWidth="30">
    <TextBox.Text>
        <Binding Path="MaxUp" Mode="TwoWay" NotifyOnValidationError="True">
            <Binding.ValidationRules>
                <Validators:MinMaxRangeValidatorRule Minimum="0" Maximum="{Binding Path=MaxLogins}" />
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

我遇到了以下错误:

'最大/最小范围验证器规则'的'Maximum'属性上不能设置'绑定'。 绑定只能在DependencyObject的DependencyProperty上设置。

请问什么是正确的绑定方式?

2个回答

9

您看到这个错误是因为MinMaxRangeValidatorRule.Maximum需要是一个依赖属性,如果您想将其绑定到MaxLogins,而它可能只是一个简单的CLR属性。

真正的问题在于,MinMaxRangeValidatorRule应该能够从ValidationRule和DependencyObject中继承(以使依赖属性可用)。在C#中不可能实现这一点。

我通过以下方式解决了类似的问题:

  1. give a name to your validator rule

    <Validators:MinMaxRangeValidatorRule Name="MinMaxValidator" Minimum="0" />
    
  2. in code behind, set the Maximum value whenever MaxLogins changes

    public int MaxLogins 
    {
        get { return (int )GetValue(MaxLoginsProperty); }
        set { SetValue(MaxLoginsProperty, value); }
    }
    public static DependencyProperty MaxLoginsProperty = DependencyProperty.Register("MaxLogins ", 
                                                                                        typeof(int), 
                                                                                        typeof(mycontrol), 
                                                                                        new PropertyMetadata(HandleMaxLoginsChanged));
    
    private static void HandleMinValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        mycontrol source = (mycontrol) d;
        source.MinMaxValidator.Maximum = (int) e.NewValue;
    }
    

太棒了,谢谢你。我太专注于让绑定工作了,以至于完全忘记了如何简单地解决这个问题。 - denis morozov

-1
我猜“MinMaxRangeValidatorRule”是自定义的东西。
实际上,错误信息非常明确,您需要将“Maximum”变量设置为依赖属性,像这样:
public int Maximum
{
    get { return (int)GetValue(MaximumProperty); }
    set { SetValue(MaximumProperty, value); }
}

// Using a DependencyProperty as the backing store for Maximum.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty MaximumProperty =
    DependencyProperty.Register("Maximum", typeof(int), typeof(MinMaxRangeValidatorRule), new UIPropertyMetadata(0));

在VS2010中,您可以通过输入“propdp”来访问依赖属性片段。


4
不能简单地添加一个依赖属性。ValidationRule 不是从 DependencyObject 继承的。 - Matt

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接