如何在依赖项的PropertyChangedCallback中绑定异步方法?

时间:2019-06-24 09:35:59

标签: c# wpf dependency-properties

我需要从依赖项属性的PropertyChangedCallback调用异步方法。

我的依赖项属性

public static readonly DependencyProperty SetTextProperty =
     DependencyProperty.Register("SetText",
typeof(string),
typeof(UserControl1),
new PropertyMetadata("",
new PropertyChangedCallback(OnSetTextChanged)));
    private async Task OnSetTextChanged()
    {
        //// My implementations.
    }

2 个答案:

答案 0 :(得分:0)

您的方法签名不正确。 PropertyChangedCallback的构造函数需要一个返回类型为void的委托,并需要两个参数:

public delegate void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)

您可以将回调标记为异步,但必须为async void,并且需要两个参数作为输入(即使您根本不使用这些参数):

private async void OnSetTextChanged(DependencyObject d, 
DependencyPropertyChangedEventArgs e)
{
    await SomeMethod();
    // other stuff
} 

答案 1 :(得分:0)

public static readonly DependencyProperty MytextDependencyProperty =
            DependencyProperty.Register("MyText", typeof(string), typeof(TestClass), new PropertyMetadata(null, PropertyChangedCallbackAsync));

    private static async void PropertyChangedCallbackAsync(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        await someMethod();
    }

静态异步无效,为我完成了窍门。