Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

c# - Async with WPF properties

I have a bound property like this:

public string MyPath
{
    get { return _mypath; }
    set
    {
        _mypath = value;
        NotifyPropertyChanged(() => MyPath);
        LoadSomeStuffFromMyPath(mypath)
    }
}

I'd like the make LoadSomeStuffFromMyPath async but I cannot await from a property. Is there a simple way to do this?

EDIT: More than one person has said not to use a property so I want to call this out. I am using WPF and this property is bound to the UI. I have to use a property.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you want to force the operation to not continue until this is complete, I would suggest making a method to handle loading and displaying your progress.

You could use a separate property to disable the UI while this loads, which could effectively "block" your user until the operation completes:

public string MyPath
{
    get { return _mypath; }
    set
    {
        _myPath = value;
        NotifyPropertyChanged(() => MyPath);
        UpdateMyPathAsync();
    }
}

public async Task UpdateMyPathAsync()
{
    this.EnableUI = false; // Stop user from setting path again....
    await LoadSomeStuffFromMyPathAsync(MyPath); 
    this.EnableUI = true;
}

This allows you to still bind, as normal, with WPF, but have your UI reflect that the operation is running (asynchronously) and display progress, etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...