【发布时间】:2020-10-22 10:13:51
【问题描述】:
我有一个简单的应用程序,当某些任务正在运行时,我会显示进度环,并在完成后立即隐藏进度环。这段代码的问题是进度条永远不会折叠。我在值转换器类中保留了一个断点,即使在值更改后它也永远不会收到 false 值。因此,ProgressRing 永远不会崩溃。请帮忙。
这是我的视图模型
public class TestVM : INotifyPropertyChanged
{
private bool _isRingVisible;
public bool IsRingVisible
{
get => _isRingVisible;
set
{
_isRingVisible = value;
OnPropertyChanged(nameof(IsRingVisible));
}
}
public TestVM()
{
Task.Run(async () => await DoSomething());
}
private async Task DoSomething()
{
IsRingVisible = true;
await Task.Delay(5000);
IsRingVisible = false; //Value set to false but when I have a break point in the value converter class, it never receives this value.
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
在 xaml 中,我有一个简单的 UI,如下所示,
<Page.Resources>
<converter:BoolToVisibilityConverter x:Key="boolToVisibility"/>
</Page.Resources>
<Grid>
<Border x:Name="BdrProgressRing"
Grid.Row="0"
Grid.RowSpan="2"
Background="Red"
VerticalAlignment="Center"
Opacity="0.6"
Visibility="{x:Bind vm.IsRingVisible,Mode=OneWay,Converter={StaticResource boolToVisibility}}">
</Border>
<ProgressRing x:Name="PgRing"
Grid.Row="0"
Grid.RowSpan="2"
Visibility="{Binding ElementName=BdrProgressRing, Path=Visibility}"
IsActive="True"
VerticalAlignment="Center"
Width="90"
Height="90"/>
</Grid>
这是我的 xaml.cs
public sealed partial class MainPage : Page
{
public TestVM vm { get; set; }
public MainPage()
{
this.InitializeComponent();
vm = new TestVM();
this.DataContext = this;
}
}
【问题讨论】:
-
谢谢它的工作。由于我在 Task 中调用它,我猜我需要使用 Dispatcher。
-
我一定会读到的,谢谢。
-
尽可能不要使用
Dispatcher。它可以使代码看起来像怪物。如果你想在执行过程中从并发Task向 UI 线程发送一些东西,你可以使用同步回调类Progress,它实现了IProgress接口。就像 while-true 一样简单。它在构造它的上下文中执行它的委托。
标签: c# uwp async-await