如何在 Xamarin Forms 中从 ViewModel 设置焦点 [英] How to set focus from ViewModel in Xamarin Forms
本文介绍了如何在 Xamarin Forms 中从 ViewModel 设置焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在执行一些异步操作后在 SearchBox
控件中设置焦点,并且我想从我的<强>视图模型.
I want to set the focus in a SearchBox
control after do some asynchronous operations, and I would like to do it from my ViewModel.
我怎么可能做到这一点?
How could I do this possible?
编辑
视图模型代码:
private bool _searchBarFocused;
public bool SearchBarFocused
{
get { return _searchBarFocused; }
set
{
_searchBarFocused = value;
base.OnPropertyChanged("SearchBarFocused");
}
}
public async Task InitializeData()
{
// Other operations...
SearchBarFocused = true;
}
查看代码隐藏代码:
protected override void OnAppearing()
{
base.OnAppearing();
(this.BindingContext as MyViewModel).InitializeData();
}
SearchBar XAML 代码:
SearchBar XAML code:
<SearchBar SearchCommand="{Binding SearchItemsCommand}">
<SearchBar.Triggers>
<DataTrigger TargetType="SearchBar"
Binding="{Binding SearchBarFocused, Mode=TwoWay}" Value="True">
<Trigger.EnterActions>
<triggers:SearchBarFocusTriggerAction Focused="True" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<triggers:SearchBarFocusTriggerAction Focused="False" />
</Trigger.ExitActions>
</DataTrigger>
</SearchBar.Triggers>
</SearchBar>
触发动作代码:
public class SearchBarFocusTriggerAction : TriggerAction<SearchBar>
{
public bool Focused { get; set; }
protected override void Invoke(SearchBar searchBar)
{
if (Focused)
searchBar.Focus();
else
searchBar.Unfocus();
}
}
推荐答案
选择之一是使用触发器(XAML 方式):
One of options is to use Triggers (XAML way):
<SearchBar x:Name="searchBar"
Text=""
Placeholder="type something">
<SearchBar.Triggers>
<DataTrigger TargetType="SearchBar"
Binding="{Binding ViewModelIsSearchBarFocused}"
Value="True">
<Trigger.EnterActions>
<local:FocusTriggerAction Focused="True" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<local:FocusTriggerAction Focused="False" />
</Trigger.ExitActions>
</DataTrigger>
<EventTrigger Event="Unfocused">
<local:UnfocusedTriggerAction />
</EventTrigger>
</SearchBar.Triggers>
</SearchBar>
public class FocusTriggerAction : TriggerAction<SearchBar>
{
public bool Focused { get; set; }
protected override async void Invoke (SearchBar searchBar)
{
await Task.Delay(1000);
if (Focused)
{
searchBar.Focus();
}
else
{
searchBar.UnFocus();
}
}
}
public class UnfocusedTriggerAction : TriggerAction<SearchBar>
{
protected override void Invoke (SearchBar searchBar)
{
YourViewModel.ViewModelIsSearchBarFocused = false;
}
}
在此处阅读更多信息:https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/triggers/
这篇关于如何在 Xamarin Forms 中从 ViewModel 设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文