WPF binding isAsync Get State

2019-03-27 23:57发布

I am using Binding IsAsync property to keep UI responsive and loading data from the get accessor of the property and proved to be a good option while using MVVM. This approach is great and doesn't need any manual code for async operations. There are few instances where my dataload is taking few seconds and during this time it is very difficult to differentiate between "no data" vs "data loading". Is there a property which I can detect the state of the binding "IsBusy" or "Loading", so that I can show some message that the loading operation is not complete?

Any help is appreciated.

2条回答
唯我独甜
2楼-- · 2019-03-28 00:04

According to the docs,

While waiting for the value to arrive, the binding reports the FallbackValue, if one is available, or the default value of the binding target property.

You can use this value to display a message to the user while the binding is loading.

查看更多
贪生不怕死
3楼-- · 2019-03-28 00:05

I know, its an old thread. But if anybody is still interested...

You could use PriorityBinding, there is a superbly explained example in this article: http://www.switchonthecode.com/tutorials/wpf-tutorial-priority-bindings

The idea is to stipulate a PriorityBinding which in turn defines several regular bindings like this:

  <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
    <TextBlock.Text>
      <PriorityBinding>
        <Binding ElementName="MainWindow" Path="Slow" IsAsync="True" />
        <Binding ElementName="MainWindow" Path="Fast" />
      </PriorityBinding>
    </TextBlock.Text>
  </TextBlock>

The order of the bindings decides the priority, with the highest priority first. In this case the Fast binding (lowest priority) will populate the textblock immediately because you might have that bound to a string property "Loading..." or "Sorting..." depending on what is happening at the time, and there is no delay.

But later when the slow async binding's property returns a value, it's higher priority means it will then take over, since it is earlier in the list, and its results will be bound instead, showing actual results.

If you need to populate a progress popup you may be able to implement that in the getter of the bound property in your ViewModel, though I haven't tried anything like this.

查看更多
登录 后发表回答