gpt4 book ai didi

wpf - 绑定(bind)和异步操作

转载 作者:行者123 更新时间:2023-12-04 15:23:43 24 4
gpt4 key购买 nike

我创建了一个内部带有 TextBlock 的窗口。我已经绑定(bind)了 Text 属性,一切正常。
但是
当我在任务中更改有界属性时,什么都不起作用!

你知道为什么吗?

Public Async Sub StartProgress()
Try
LoadingText = "text 1" 'Works perfect

Dim fResult As Boolean = Await LoadModules()

If Not fResult Then
MessageBox.Show(Me.Error)
End If

m_oView.Close()
Catch ex As Exception
Msg_Err(ex)
End Try
End Sub

Public Async Function LoadModules() As Task(Of Boolean)
Try
Await Task.Delay(3000)

LoadingText = "text 2" 'Nothing Happens

Await Task.Delay(5000)

LoadingText = "complete" 'Nothing Happens

Await Task.Delay(3000)

Return True
Catch ex As Exception
Me.Error = ex.Message
Return False
End Try
End Function

文本 2 和 3 从未显示。如果我动态更改 textblcok 的文本(例如:m_oView.txtLoadingText.Text)它工作正常(但这不是解决方案)

编辑
这是 ViewModel Base,每个 ViewModel 都实现了该类。

Public Class VM_Base
Implements IDisposable
Implements INotifyPropertyChanged

Private m_oDS As MxDataSet
Public Property [Error] As String

Public Event PropertyChanged As PropertyChangedEventHandler _
Implements INotifyPropertyChanged.PropertyChanged

Protected Sub New()
m_oDS = New MxDataSet

End Sub

Protected Overrides Sub Finalize()
Try
Me.Dispose(False)
Debug.Fail("Dispose not called on ViewModel class.")
Finally
MyBase.Finalize()
End Try
End Sub

Public Sub Dispose() Implements IDisposable.Dispose
Me.Dispose(True)
GC.SuppressFinalize(Me)
End Sub

Protected Overridable Sub Dispose(disposing As Boolean)
End Sub

Protected Overridable Sub OnPropertyChanged(propertyName As String)
Me.EnsureProperty(propertyName)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
End Sub

<Conditional("DEBUG")> _
Private Sub EnsureProperty(propertyName As String)
If TypeDescriptor.GetProperties(Me)(propertyName) Is Nothing Then
Throw New ArgumentException("Property does not exist.", "propertyName")
End If
End Sub
End Class

如何调用 StartProgress:

<i:Interaction.Triggers>
<i:EventTrigger EventName="ContentRendered">
<i:InvokeCommandAction Command="{Binding DataContext.WindowsActivatedCommand,ElementName=fLoading}" />
</i:EventTrigger>
</i:Interaction.Triggers>

编辑
将 TextBlock 绑定(bind)到属性

Public Property LoadingText As String
Get
Return m_sLoadingText
End Get
Set(value As String)
m_sLoadingText = value
OnPropertyChanged("LoadingText")
End Set
End Property

<TextBlock x:Name="txtLoading" Width="450"
Grid.Row="1" VerticalAlignment="Center"
HorizontalAlignment="Left"
TextWrapping="Wrap" Text="{Binding LoadingText}">
</TextBlock>

最佳答案

以下是有关确保源自非 UI 线程的调用正确调用 UI 方法所需做的详细答案:

Ensuring that things run on the UI thread in WPF

关于wpf - 绑定(bind)和异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17275065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com