ValidationRule中的wpf绑定属性

kay*_*cee 4 validation wpf binding

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

  1. TotalLoginsTextBox

  2. UploadsLoginsTextBox

我想限制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>
Run Code Online (Sandbox Code Playgroud)

问题我得到以下错误:

无法在"MinMaxRangeValidatorRule"类型的"最大"属性上设置"绑定".'绑定'只能在DependencyObject的DependencyProperty上设置.

什么是绑定的正确方法?

sim*_*im1 8

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

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

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

  1. 为验证者规则命名

    <Validators:MinMaxRangeValidatorRule Name="MinMaxValidator" Minimum="0" />
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在代码隐藏中,每当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;
    }
    
    Run Code Online (Sandbox Code Playgroud)


Lou*_*ann -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));
Run Code Online (Sandbox Code Playgroud)

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

  • 您不能简单地添加依赖属性。ValidationRule 不扩展自 DependencyObject (4认同)