我的Xamarin.Forms应用程序有一个ListView,其中每个ViewCell都包含一个Editor。只要轻按Editor,就会触发Focused
事件,即使未按键盘上的Done或Enter,也会触发Completed
事件。
有人知道发生了什么,我该如何解决?
改为使用TextChanged事件https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/text/editor
void EditorTextChanged (object sender, TextChangedEventArgs e)
{
var oldText = e.OldTextValue;
var newText = e.NewTextValue;
}
您认为遇到的问题是,当您轻按Editor时,当您轻按另一个时,第一个将反应为Completed
,而新的轻按将反应为Focused
。从那里开始,每次您点击编辑器时,两个EventHandler都将被调用:Completed
表示先前的Editor Completed!和Focused
表示新的编辑器Focused。
免责声明:下面显示的代码仅是建议一种解决此问题的方法,我绝不打算说这是最佳代码或生产代码。
我假设您决定使用正在使用的方法,因为您认为这是最适合您的用例的方法。
话虽如此,如果我必须解决您的问题,我将扩展用于馈送ListView的对象,使其包含id,然后检索该< EventHandler
中的[id,以便确切地知道哪个项目正在触发event。
public class People
{
public int id { get; set; }
public String FullName { get; set; }
public string Location { get; set; }
public Boolean IsVisible { get; set; }
}
然后使用我编写的OnAppearing
方法
protected override void OnAppearing() { List<People> i = new List<People>() { new People() { id = 0 }, new People() { id = 1 } }; BindingContext = i; base.OnAppearing(); }
在中,我创建了一个简单的ListView asXAML
<ContentPage.Content>
<ListView ItemsSource="{Binding .}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<Editor Focused="Editor_Focused"
Completed="Editor_Completed"/>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentPage.Content>
因此,在后面的代码中,我能够在
EventHandler
中做出相应的反应private void Editor_Focused(object sender, FocusEventArgs e) { var tappedItemId = ((People)((Editor)sender).BindingContext).id; } private void Editor_Completed(object sender, EventArgs e) { var tappedItemId = ((People)((Editor)sender).BindingContext).id; }
希望您阅读本文后能看清您的问题。快乐编码!