How to keep button enabled while performing asynchronous task

81 Views Asked by At

In my xaml I have a Button and a TextBlock

<TextBlock Text="{Binding AText}" FontSize="20"/>
<Button Content="Click" Command="{Binding MyCommand}" Grid.Row="1"/>

and in my ViewModel I have following Code

let aText = self.Factory.Backing(<@ self.AText @>, "Initial Text")
let asyncTask x = async {
    self.AText <- "Loading"
    do! Async.Sleep(5000)
    self.AText <- "Loaded"
} 

member self.AText with get() = aText.Value and set(v) = aText.Value <- v    
member self.MyCommand = self.Factory.CommandAsyncChecked(asyncTask, fun _ -> true)

When I click the button, It gets disabled and remains so until it finishes the asyncTask. I thought that setting canExecute as true will change the behavior but it did not!

How to control the behaviour of the button?

1

There are 1 best solutions below

5
On BEST ANSWER

The Async command support in FSharp.ViewModule was designed specifically so that the commands disable while operating, in order to prevent them from occurring multiple times.

If you don't want that behavior, the simplest option is to just use a normal command, and start the async workflow manually:

let asyncTask () = async {
    self.AText <- "Loading"
    do! Async.Sleep(5000)
    self.AText <- "Loaded"
} |> Async.Start

member self.MyCommand = self.Factory.Command asyncTask

The normal command behavior will always remain enabled.