由于Xamarin 2.4(并切换到.Net Standard而不是PCL),我使用自己的行为得到以下错误(XAMLC是:
No property, bindable property, or event found for 'MaxLength', or mismatching type between value and property.
这是实现(非常简单):
using Xamarin.Forms;
namespace com.rsag.xflib.Behaviors
{
/// <summary>
/// Constrain the number of charachters on entry to the given length
/// </summary>
public class MaxLengthEntryBehavior : Behavior<Entry>
{
/// <summary>
/// Value to prevent constraint
/// </summary>
public const int NOT_CONSTRAINED = 0;
/// <summary>
/// Bindable property for <see cref="MaxLength" />
/// </summary>
public static readonly BindableProperty MaxLengthProperty = BindableProperty.Create(nameof(MaxLength),
typeof(int), typeof(MaxLengthEntryBehavior), NOT_CONSTRAINED, validateValue: ValidateMaxValue);
/// <summary>
/// Max. length for the text (-1: not constrained)
/// </summary>
public int MaxLength
{
get => (int) GetValue(MaxLengthProperty);
set => SetValue(MaxLengthProperty, value);
}
private static bool ValidateMaxValue(BindableObject bindable, object value)
{
if (value is int intValue)
{
return intValue >= NOT_CONSTRAINED;
}
return false;
}
/// <inheritdoc />
protected override void OnAttachedTo(Entry bindable)
{
if (bindable != null)
{
bindable.TextChanged += OnTextChanged;
}
}
/// <inheritdoc />
protected override void OnDetachingFrom(Entry bindable)
{
if (bindable != null)
{
bindable.TextChanged -= OnTextChanged;
}
}
private void OnTextChanged(object sender, TextChangedEventArgs e)
{
if (MaxLength == NOT_CONSTRAINED)
{
return;
}
if (string.IsNullOrEmpty(e.NewTextValue))
{
return;
}
var entry = (Entry) sender;
if (e.NewTextValue.Length > MaxLength)
{
entry.Text = e.NewTextValue.Substring(0, MaxLength);
}
}
}
}
App中的用法也非常简单:
<Entry Text="{Binding ServerPort.Value Keyboard="Numeric">
<Entry.Behaviors>
<libBehav:MaxLengthEntryBehavior MaxLength="{x:Static ac:Constants.MAX_PORT_LENGTH}" />
</Entry.Behaviors>
</Entry>
此编译适用于文字MaxLength="10"
和Bindings MaxLength="{StaticResource MyValue}"
,但不适用于静态类的值。我需要XAML和一些C#代码中的值,所以我想使用Constants
类。
静态类中的值定义如下:
public const int MAX_PORT_LENGTH = 5;
修改2018-01-09
问题似乎在于使用内部类。以下作品:
MaxLength="{x:Static ac:Constants.MAX_PORT_LENGTH}"
但不是这样:
MaxLength="{x:Static ac:Constants.ServerConstraints.MAX_PORT_LENGTH}"
答案 0 :(得分:1)
今天我遇到了类似的问题,结果发现我的XAML中缺少'}'。看起来你在这一行上遗漏了'}':
<Entry Text="{Binding ServerPort.Value Keyboard="Numeric">
^-- here
答案 1 :(得分:0)
最后我找到了解决方案
在previos版本中(我认为静态setter未被编译,但在运行时被解释)语法是.
来访问内部类:
MaxLength="{x:Static ac:Constants.ServerConstraints.MAX_PORT_LENGTH}"
在较新版本的Xamarin.Forsm中,我必须用 +
代表内部类。
MaxLength="{x:Static ac:Constants+ServerConstraints.MAX_PORT_LENGTH}"