ValidationRule中的wpf绑定属性

时间:2011-09-17 16:51:19

标签: wpf binding validation

我有一个包含2个文本框的表单:

  
      
  1. TotalLoginsTextBox

  2.   
  3. UploadsLoginsTextBox

  4.   

我想限制UploadsLoginsTextBox,因此文本的最大输入将是TotalLoginsTextBox的值。 我也在使用值转换器,所以我尝试绑定最大值:

这是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>

问题我收到以下错误:

  

无法在类型的“最大”属性上设置“绑定”   'MinMaxRangeValidatorRule'。 '绑定'只能在a上设置   DependencyObject的DependencyProperty。

进行绑定的正确方法是什么?

2 个答案:

答案 0 :(得分:8)

您会看到此错误,因为 MinMaxRangeValidatorRule.Maximum 如果要将其绑定到 MaxLogins ,则需要是DependencyProperty,而它可能是一个简单的CLR属性。

真正的问题是MinMaxRangeValidatorRule应该能够从DependencyObject继承ValidationRule AND(以使Dependency Properties可用)。这在C#中是不可能的。

我用这种方式解决了类似的问题:

  1. 为验证者规则命名

    <Validators:MinMaxRangeValidatorRule Name="MinMaxValidator" Minimum="0" />
    
  2. 在后面的代码中
  3. ,每当MaxLogins更改时设置最大值

    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;
    }
    

答案 1 :(得分:-1)

我猜测“MinMaxRangeValidatorRule”是定制的。

实际上错误消息非常明确,您需要将“最大”变量设为依赖属性,如下所示:

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”来访问依赖项属性代码段。

相关问题