【问题标题】:awaiting default value of DependencyProperty等待 DependencyProperty 的默认值
【发布时间】:2020-05-24 18:44:33
【问题描述】:

我有DependencyPropertyStorageFolder 类型:

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

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

【问题讨论】:

  • 属性在语义上与字段相同,不应该是异步的。如果需要支持异步,请使用 getter / setter 方法。

标签: c# async-await dependency-properties


【解决方案1】:

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

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

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

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

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

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

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


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

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

【讨论】:

    猜你喜欢
    • 2016-09-16
    • 1970-01-01
    • 2012-07-31
    • 2019-08-08
    • 1970-01-01
    • 2017-06-28
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多