发布:2021/10/20 15:19:28作者:管理员 来源:本站 浏览次数:1013
我想在做一些异步操作后将焦点设置在SearchBox控件中,我想从我的ViewModel中做到这一点.
我怎么能这样做?
编辑
ViewModel代码:
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 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方式):
<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;
}
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4