Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

Can't figure out where the error is.

Xamarin.Forms version: 4.8.0.1451

.NET Standard 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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
489 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to click the Search Icon from Input Keyboard, then the SearchCommand will be invoked.

enter image description here

Then the 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. It will make the isInitialized = true later than invoke TestCommand code.

Therefore, TestCommand can not be executed all the time.

The solution that you need to comment this line code 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);
}
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...