我有一个用于输入手机号码的条目,我希望在删除行为中输入的手机号码时按下返回按钮。
我在后面的视图代码中尝试了OnBackButtonPressed()
。但是,删除条目文本时不会触发。我已经推荐了许多网站,但没有任何明确的解决方案。请提出您的宝贵建议。
<Entry x:Name="phoneEntry" Placeholder="Phone Number" FontSize="14" PlaceholderColor="Gray" Text="{Binding Number}" HorizontalOptions="FillAndExpand" Keyboard="Telephone">
<Entry.Behaviors>
<behavior:EntryBehavior CommandParameter="{x:Reference phoneFormat}"/>
</Entry.Behaviors>
</Entry>
电话号码格式行为
public class EntryBehavior : Behavior<Entry>
{
public object CommandParameter
{
get { return (object)GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public static readonly BindableProperty CommandParameterProperty =
BindableProperty.Create("CommandParameter", typeof(object), typeof(EntryBehavior));
protected override void OnAttachedTo(Entry bindable)
{
base.OnAttachedTo(bindable);
bindable.TextChanged += Bindable_TextChanged;
}
private void Bindable_TextChanged(object sender, TextChangedEventArgs args)
{
if (CommandParameter != null)
{
var index = (CommandParameter as MyList).SelectedIndex;
if (index == 0 && ((Entry)sender).Text.Length < 14)
{
var value = args.NewTextValue;
if (string.IsNullOrEmpty(args.OldTextValue) && !args.NewTextValue.Contains("("))
{
((Entry)sender).Text = "(" + value;
return;
}
if (value.Length == 4)
{
((Entry)sender).Text += ") ";
return;
}
if (value.Length == 9)
{
((Entry)sender).Text += "-";
return;
}
}
if (index == 1 && ((Entry)sender).Text.Length < 14)
{
var value = args.NewTextValue;
if (((Entry)sender).Text.Length == 1 && !((Entry)sender).Text.Contains("("))
{
((Entry)sender).Text += "(";
return;
}
if (value.Length == 5)
{
((Entry)sender).Text += ") ";
return;
}
if (value.Length == 7 && !((Entry)sender).Text.Contains(" ") && !((Entry)sender).Text.Contains(")"))
{
((Entry)sender).Text += " ";
return;
}
if (value.Length == 10)
{
((Entry)sender).Text += "-";
return;
}
}
((Entry)sender).Text = args.NewTextValue;
}
}
protected override void OnDetachingFrom(Entry bindable)
{
base.OnDetachingFrom(bindable);
}
}
我要根据类型设置电话号码
Type1 :(xxx)xxx-xxxx
Type2 :x(xxx)xxx-xxxx
答案 0 :(得分:1)
第一个解决方案
假设您使用绑定
<Entry Text="{Binding EntryText}" HorizontalOptions="Center"/>
在您的ViewModel中,将EntryText实现更改为
private string entryText;
public string EntryText
{
get => entryText;
set
{
if (!string.IsNullOrEmpty(entryText) && value.Length < entryText.Length)
{
Console.WriteLine("Char was deleted");
}
SetProperty(ref entryText, value);
}
}
第二个解决方案
您不使用MVVM模式,而是在后面的代码中执行所有操作。将输入行更改为
<Entry Grid.Row="2" TextChanged="Handle_TextChanged" HorizontalOptions="Center"/>
现在,创建一个Handle_TextChanged
实现:
public void Handle_TextChanged(object sender, TextChangedEventArgs e)
{
if (!(sender is Entry label))
{
return;
}
if (!string.IsNullOrEmpty(e.OldTextValue) && e.NewTextValue.Length < e.OldTextValue.Length)
{
Console.WriteLine("Char deleted");
}
}