简体   繁体   English

使用谓词绑定在命令上的搜索栏不起作用。 Xamarin.Forms

[英]Search bar bound on command with predicate don't work. Xamarin.Forms

After such a binding, it is impossible to focus on the search bar.这样绑定之后,就不可能专注于搜索栏了。 When tapped nothing happens.轻按时没有任何反应。 After calling ChangeCanExecute() SearchBar's property IsEnabled changes to true and that's all.调用ChangeCanExecute() SearchBar 的属性IsEnabled后更改为true ,仅此而已。

Can't figure out where the error is.无法弄清楚错误在哪里。

Xamarin.Forms version: 4.8.0.1451 Xamarin.Forms 版本:4.8.0.1451

.NET Standard 2.1 .NET 标准2.1

My view:我的观点:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:SearchBarTest"
             x:Class="SearchBarTest.MainPage">
    <ContentPage.BindingContext>
        <local:TestViewModel/>
    </ContentPage.BindingContext>
    <StackLayout>
        <SearchBar SearchCommand="{Binding TestCommand}"/>
    </StackLayout>
</ContentPage>

View model:查看 model:

internal class TestViewModel
{
    private bool isInitialized;

    public Command TestCommand { get; }

    public TestViewModel()
    {
        Task.Run(() =>
        {
            Thread.Sleep(5000);

            isInitialized = true;

            Debug.WriteLine($">>> Initialized: {isInitialized}");

            TestCommand.ChangeCanExecute();
        });

        TestCommand = new Command(() =>
        {
            Debug.WriteLine(">>> Command invoked.");
        }, () => isInitialized);
    }
}

You need to click the Search Icon from Input Keyboard , then the SearchCommand will be invoked.您需要单击Input Keyboard中的Search Icon ,然后SearchCommand将被调用。

在此处输入图像描述

Then the output:然后是 output:

12-31 11:20:29.425 I/AssistStructure(31728): Flattened final assist data: 2560 bytes, containing 1 windows, 9 views
[0:] >>> Command invoked.

==========================update=============================== ===========================更新======================= ========

I have checked the sample, the problem has been found.我检查了样品,发现问题。 You add Thread.Sleep(5000) in the Task thread.您在任务线程中添加Thread.Sleep(5000) It will make the isInitialized = true later than invoke TestCommand code.它会使isInitialized = true晚于调用TestCommand代码。

Therefore , TestCommand can not be executed all the time.因此TestCommand不能一直执行。

The solution that you need to comment this line code Thread.Sleep(5000) .您需要注释此行代码Thread.Sleep(5000)解决方案

...
public TestViewModel()
{
    Task.Run(() =>
    {
        //Thread.Sleep(5000);

        isInitialized = true;

        Debug.WriteLine($">>> Initialized: {isInitialized}");

        TestCommand.ChangeCanExecute();
    });

    TestCommand = new Command(() =>
    {
        Debug.WriteLine(">>> Command invoked.");
    }, () => isInitialized);
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM