wpf - F# wpf 异步命令完成状态

标签 wpf xaml mvvm f#

我一直在使用 F# Viewmodule 尝试异步命令。问题是当我单击按钮时,命令被执行,但之后按钮保持禁用状态。

Xaml:

<Button Content="start async worker" Command="{Binding StartAsyncCommand}" />

View 模型:

type MainViewModel() as me = 
  inherit ViewModelBase()
//...
member __.StartAsyncCommand = me.Factory.CommandAsync(fun _ -> async { return () } )

我做错了什么?

编辑:

感谢@FoggyFinder,我们确定问题实际上出在 App.fs 文件上:

open System
open FsXaml
open System.Windows

type MainWindow = XAML< "MainWindow.xaml">

[<STAThread>]
[<EntryPoint>]
let main argv = 
  Application().Run(MainWindow().Root)

创建基本上空的 App.xaml 并像这样开始:

module main

open System
open FsXaml

type App = XAML<"App.xaml">

[<STAThread>]
[<EntryPoint>]
let main argv =
    App().Root.Run()

修复了它。如果有人知道对此的解释,请随时提供。

最佳答案

What am I doing wrong?

问题在于,当您构建 ViewModel 层时,没有 SynchronizationContext,这意味着将事物推回到 UI 上下文的内部代码无法正常工作。

您可以通过在调用 Application.Run() 之前在入口点的开头添加以下内容来解决此问题:

if SynchronizationContext.Current = null then
    DispatcherSynchronizationContext(Dispatcher.CurrentDispatcher)
    |> SynchronizationContext.SetSynchronizationContext

这将确保创建 Dispatcher 并安装有效的 SynchronizationContext,并且可能会为您解决问题。

关于wpf - F# wpf 异步命令完成状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554054/

相关文章:

c# - 使用 MVVM (C# WPF) 如何在应用程序初始化时将设置显示到它们各自的控件中?

c# - 错误 : Could not load file or assembly 'Microsoft. Practices.ServiceLocation,版本 = 1.0.0.0

c# - WPF 处理耗时的 UI 线程更新

wpf - WPF DataGrid行标题不可见

c++ - Vista 窗口标题中的图片(标识)

c# - 使 Button IsEnabled 状态取决于两个文本框

wpf - 正确使用命令 (MVVM)

xaml - 如何更改AppBarButton圆圈和图标颜色Windows Phone 8.1页面底栏

c# - WPF mvvm 绑定(bind),获取/设置值 : issue with preventing update value

.net - 用于 wpf mvvm 的 MVVM 工具包(模板)和 XAML powertoys 工作吗?