假設我有一個類通過TCP流接收數據,解析它並相應地更改它的屬性。WPF等待變量更改然後更新UI
public static class SomeClass
{
static bool myBool;
static string myMessage;
public static void ToggleBool()
{
myBool = !myBool;
// Do some other stuff here
}
public static UpdateMessage(string message)
{
System.Diagnostics.Debug.WriteLine(message);
ProcessMessage(message);
myMessage = message;
}
}
現在我想要做的就是擁有一個WPF「調試窗口」,它將直觀顯示設置。我想基本上運行一個循環,相應地更新部分窗口。
喜歡的東西:
public partial class LogWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public Async Task UpdateUI()
{
while(checkForUpdates)
{
myCheckbox.IsChecked = await SomeClass.UpdatedBoolValue();
string newMessage = await SomeClass.NewMessageRCVD();
txtBox.Append(newMessage);
}
}
}
但是,有2點明顯的問題。其中一個,我不知道如何通過不斷檢查while循環來創建一個不會燒壞CPU的函數。我想我可以使用getter/setter方法。二,我必須更新兩個,以便該循環再次運行。
這是最好的方法是什麼?如何更新需要更新的用戶界面部分?
編輯:類似的問題:Write an Async method that will await a bool
使用定時器更新某個intervall中的所有值。 – CSharpie
如果您使用Caliburn Micro或ReactiveUI,他們都有一些pub-sub實現用於應用程序內消息分派,可以準確解決這些問題。 –