13

いくつかの非同期操作を行った後、コントロールにフォーカスを設定したいと思います。ViewModelから行いたいと思います。SearchBox

どうすればこれを可能にできますか?

編集

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();
    }
}
4

3 に答える 3

9

オプションの 1 つは、トリガー (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;
    }
}

詳細はこちら: https://developer.xamarin.com/guides/cross-platform/xamarin-forms/working-with/triggers/

于 2015-08-25T23:01:13.807 に答える