我有一個 WPF 應用程式,它將在單擊按鈕時運行一堆可執行檔案(通過行程)。在表單中,有一個 TextBlock,我想為每個可執行檔案填寫說明。問題是,TextBlock 在 Process 完成之前不會更新。我檢查了除錯器中的 TextBlock.Text 值,它有正確的文本,但沒有顯示。有沒有辦法強制 WPF TextBlock 顯示其當前的 Text 屬性?
這是我的代碼:
主視窗.xaml
<Grid>
<TextBlock x:Name="InstructionsTextBlock" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" Text="{Binding Instructions.Instructions, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Height="200" Width="287" Background="#FFB0BBAD"/>
<Button Margin="52,223,525,149" x:Name="UpdateTextBlockAndRunExe" Content="Update TextBlock and run .exe" Click="UpdateTextBlockAndRunExe_Click"></Button>
</Grid>
主視窗.xaml.cs
public partial class MainWindow: Window {
MainViewModel _main = new MainViewModel();
public MainWindow() {
InitializeComponent();
DataContext = _main;
_main.SetInstructions("Initial Instructions");
}
private void UpdateTextBlockAndRunExe_Click(object sender, RoutedEventArgs e) {
_main.SetInstructions("Before Exe - I want this to show up");
string executablePath = Path.Combine(Utils.getResourcesDirectory(), "uniws", "uniws.exe");
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.FileName = executablePath;
startInfo.WindowStyle = ProcessWindowStyle.Normal;
using(Process exeProcess = Process.Start(startInfo)) {
exeProcess.WaitForExit();
}
_main.SetInstructions("After Exe - I want to end on this");
}
}
主視圖模型.cs
public class MainViewModel {
public InstructionsViewModel Instructions {
get;
private set;
}
public MainViewModel() {
Instructions = new InstructionsViewModel();
}
public void SetInstructions(string instructions) {
Instructions.Instructions = instructions;
}
}
說明ViewModel.cs
public class InstructionsViewModel: ObservableObject {
private string _instructions;
public string Instructions {
get {
if (string.IsNullOrEmpty(_instructions))
return "No instructions";
return _instructions;
}
set {
_instructions = value;
OnPropertyChanged("Instructions");
}
}
}
ObservableObject.cs
public class ObservableObject: INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name) {
if (PropertyChanged != null) {
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
在行程執行期間:

除錯模式 - 顯示設定了 Text 屬性:

uj5u.com熱心網友回復:
簡而言之,沒有。更新需要在 GUI 執行緒上完成,但您通過呼叫 WaitForExit 來阻止它。
處理這個問題的最好方法是使用異步編程。將您的點擊處理程式更改為異步,然后等待每個行程完成使用此問題答案中WaitForExitAsync的函式。
uj5u.com熱心網友回復:
您可以使用調度程式:
Dispatcher.Invoke(() => _main.SetInstructions("Before Exe - I want this to show up"), DispatcherPriority.Send);
但我會推薦 async ,就像 Mark 已經做過的那樣。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/486018.html
上一篇:兩個依賴控制元件上的WPF擴展器
