我有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
如何通过异步操作为依赖属性设置默认值?
让我分享我对这个问题的看法。
让我们忘记DependencyProperty
一分钟。您想要实现的是在静态对象初始化期间调用异步函数。
static ComplexObject co = new ComplexObject(await GetSomeValueAsync());
通常来说,为对象分配空间应尽可能快且没有错误。仅当出于任何原因拒绝分配时,都应该引发错误。
让我们假设您正在同步调用异步代码(请不要这样做,它仅用于演示目的:]
static ComplexObject co = new ComplexObject(GetSomeValueAsync().GetAwaiter().GetResult());
如果您的I / O相关操作失败怎么办?如果花了几分钟才得到答复怎么办?无论哪种情况,都违反了对象分配的承诺。
我建议考虑其他方法来注入默认文件夹: