Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在Xamarin表单中从ViewModel设置焦点_C#_Xaml_Focus_Viewmodel_Xamarin Forms - Fatal编程技术网

C# 如何在Xamarin表单中从ViewModel设置焦点

C# 如何在Xamarin表单中从ViewModel设置焦点,c#,xaml,focus,viewmodel,xamarin-forms,C#,Xaml,Focus,Viewmodel,Xamarin Forms,在执行一些异步操作后,我想在搜索框控件中设置焦点,我想从我的视图模型中设置焦点 我怎么可能做到这一点 编辑 视图模型代码: private bool _searchBarFocused; public bool SearchBarFocused { get { return _searchBarFocused; } set { _searchBarFocused = value;

在执行一些异步操作后,我想
搜索框
控件中设置焦点,我想从我的视图模型中设置焦点

我怎么可能做到这一点

编辑

视图模型代码:

    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();
    }
搜索栏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();
    }
}
公共类SearchBarFocustriggeration:Triggeration
{
公共布尔集中{get;set;}
受保护的覆盖无效调用(搜索栏搜索栏)
{
如果(聚焦)
searchBar.Focus();
其他的
searchBar.Unfocus();
}
}

选项之一是使用触发器(XAML方式):


public类focustriggeration:triggeration
{
公共布尔集中{get;set;}
受保护的重写异步void调用(搜索栏搜索栏)
{
等待任务。延迟(1000);
如果(聚焦)
{
searchBar.Focus();
}
其他的
{
searchBar.UnFocus();
}
}
}
公共类非焦点触发操作:触发操作
{
受保护的覆盖无效调用(搜索栏搜索栏)
{
YourViewModel.ViewModelIsSearchBarFocused=false;
}
}

请在此处阅读更多信息:

这是一个示例,说明了我的做法,在此之前,我使用MessagingCenter

在xaml中,需要为要进行聚焦的对象指定一个x:Name

<!-- PICKER's DEFINITION -->
<DatePicker
    x:Name="Datepicker"
    Date="{Binding SelectedDate, Mode=TwoWay}"
    IsEnabled="true"
    IsVisible="false">
</DatePicker>

然后,您必须在按钮的命令参数中引用该控件,例如,在本例中,我使用工具栏项

<!-- MENU TOOLBAR -->
<ContentPage.ToolbarItems>
    <ToolbarItem
        Command="{Binding ShowCalendarCommand}"
        Icon="Calendar"
        CommandParameter="{x:Reference Datepicker}" />
</ContentPage.ToolbarItems>

然后在vm命令中:

#region toolbar commands

public ICommand ShowCalendarCommand => new RelayCommand<Object>(ShowCalendar);

#endregion

private void ShowCalendar(Object obj)
{
    var calendar = (DatePicker)obj;
    calendar.Focus();
    //  MessagingCenter.Send(this, "Calendar");
}
#区域工具栏命令
public ICommand ShowCalendar=>newrelaycommand(ShowCalendar);
#端区
私有void ShowCalendar(对象obj)
{
var calendar=(日期选择器)obj;
calendar.Focus();
//发送(本“日历”);
}

我通过在viewmodel中将contentpage作为一个参数传递来解决我的问题

BindingContext = new YourViewModel(this);
并在视图模型中创建了一个属性

public ContentPage m_View { get; set; }
然后从构造函数中设置此属性的值

 public YourViewModel(ContentPage view)
    {
        m_View = view;
    }
然后使用DatePicker的名称设置其焦点

  var DatePicker = m_View.FindByName("YourDatePickerName") as DatePicker;
  DatePicker.Focus();
我的日期选择器代码是

 <DatePicker x:Name="YourDatePickerName"
             Date="{Binding SelectedDate}" />


谢谢你的回复,丹尼尔。我在我的项目中使用了您的方法,它似乎是有效的,但是调用方法只是在我第一次将ViewModelIsSearchBarFocused值指定为true时才出现的。其余时间不调用此方法…您知道为什么吗?您的ViewModel是否正确实现了IOnNotifyPropertyChanged?我需要您的ViewModel代码来了解原因。是的。我刚刚用我正在使用的源代码更新了这个问题。它在第一次调用InitializeData()方法时起作用,但在第二次调用时不起作用……我认为这是因为当焦点在UI中丢失时,ViewModelIsSearchBarFocused属性没有设置为false。可能吗。您是否尝试使用任务。先延迟再集中?我修改了我的例子。2.您真的需要在绑定中使用
Mode=TwoWay
吗?例如,如果每次在条目中键入字符时都要将焦点放回视图,该怎么办。假设我使用entry或SearchBar搜索输入的每个字符,我希望进行过滤。但我的过滤逻辑会导致条目失去焦点,所以在最后我想重新关注该条目,以便用户可以键入下一个字符。