首页 > 解决方案 > 等待 DependencyProperty 的默认值

问题描述

我有DependencyProperty以下StorageFolder类型:

public StorageFolder FolderForVideos
{
    get { return (StorageFolder)GetValue(FolderForVideosProperty); }
    set { SetValue(FolderForVideosProperty, value); }
}
public static readonly DependencyProperty FolderForVideosProperty =
  DependencyProperty.Register("FolderForVideos", typeof(StorageFolder), typeof(MyControl), new PropertyMetadata(null);

我需要默认值作为FolderForVideo视频保存文件夹:

StorageFolder folder= (await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos)).SaveFolder;

等待是这里的问题。因为显然我不能使用类似的东西:

public static readonly DependencyProperty FolderForVideosProperty =
  DependencyProperty.Register("FolderForVideos", typeof(StorageFolder), typeof(MyControl), new 
PropertyMetadata((await StorageLibrary.GetLibraryAsync(KnownLibraryId.Videos)).SaveFolder));

因为 Error CS1992 The 'await' operator can only be used when contained within a method or lambda expression marked with the 'async' modifier FrameByFramePlayer C:\Users\toted\Desktop\Repos\videodetpl\FrameByFramePlayer\Custom\CameraControl.xaml.cs 110 Active

如何从异步操作中设置依赖属性的默认值?

标签: c#async-awaitdependency-properties

解决方案


让我分享一下我对这个问题的看法。

让我们忘记DependencyProperty一分钟。您要实现的是在静态对象初始化期间调用异步函数。

static ComplexObject co = new ComplexObject(await GetSomeValueAsync());

一般来说,为对象分配空间应该是快速的并且尽可能没有错误。仅当分配因任何原因被拒绝时才应引发错误。

让我们假设您正在同步调用您的异步代码(请不要这样做,这只是为了演示目的):

static ComplexObject co = new ComplexObject(GetSomeValueAsync().GetAwaiter().GetResult());

如果您的 I/O 相关操作失败怎么办?如果需要几分钟才能得到回复怎么办?无论哪种情况,您都违背了对象分配的承诺。


我建议考虑注入默认文件夹的替代方法:

  • 在部署期间,如果它是特定于环境的
  • 在启动期间,如果来自配置
  • 在构建期间,它可以是常量还是来自资源文件

推荐阅读