行为-视图模型绑定

5

我正在尝试编写一个简单的行为,用于验证输入值是否在某个范围内,其中包括最大和最小值:

<Entry Text="{Binding Quantity, Mode=TwoWay}">
  <Entry.Behaviors>
    <ui:ValueInRangeValidator x:Name="QtyValidator" MinValue="1" MaxValue="10"/>
  </Entry.Behaviors>
</Entry>

这个可以正常运作,但是当我尝试添加绑定,例如:MaxValue="{Binding MaxVal}"时,值保持它的默认值。

我在我的行为中使用以下内容:

public static BindableProperty MaxValueProperty =
        BindableProperty.Create("MaxValue", typeof(decimal?), typeof(ValueInRangeValidator));
public decimal? MaxValue
{
    get { return (decimal?)GetValue(MaxValueProperty); }
    set
    {
        SetValue(MaxValueProperty, value);
        OnPropertyChanged();
    }
}

我还尝试在BindableProperty上设置属性更改事件,但似乎从未触发。我知道ViewModel是正确的,因为将相同的属性绑定到标签可以显示该值。

1个回答

3

试试这样做:

<Entry x:Name="Entry1" 
       BindingContext="{Binding}" 
       Text="{Binding Quantity, 
       Mode=TwoWay}">
    <Entry.Behaviors>
        <ui:ValueInRangeValidator x:Name="QtyValidator" 
            MinValue="1" 
            MaxValue="{Binding BindingContext.MaxVal, Source={x:Reference Entry1}}"/>
    </Entry.Behaviors>
</Entry>

我将名称添加到父View中,这意味着我无需重新绑定或命名Entry控件,并且在需要用到它的多个位置时可以访问整个View。感谢您的帮助! - Ben Catterall
这正是我想要的。顺便提一下,输入框的OnEntryTextChanged事件会在MaxValue绑定到值之前触发。有什么办法可以阻止它吗? - Hasitha
@Hasitha 抱歉,我恐怕不知道。 - Yehor Hromadskyi

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