【发布时间】:2017-12-01 08:04:54
【问题描述】:
由于 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" 和绑定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}"
【问题讨论】:
标签: xamarin.forms behavior .net-standard attachedbehaviors