我很確定我錯過了一些非常小的東西,但我一生都無法弄清楚我哪里出錯了。我試圖將我的數據網格綁定到實際上正在獲取輸入的 ConsoleLines 屬性,我調試了它并且 ConsoleLines 包含多個字符串。但由于某種原因,它沒有更新 UI 并將線條添加到 gridview .. 或者從技術上講是 TextBlock。所以我的 MainWindows 設置是這樣的public partial class MainWindow : Window { Server Server = new Server(); public MainWindow() { InitializeComponent(); DataContext = new MasterViewModel(); } private void BtnStart_OnClick(object sender, RoutedEventArgs e) { Server.StartServer(); } }如您所見,我將 DataContext 設置為 MasterViewModel 的一個新實例,如下所示public class MasterViewModel { public Server Server { get; } = new Server(); }這是我的服務器類public class Server : INotifyPropertyChanged { public Process pServer; public Server() { } public ObservableCollection<string> ConsoleLines { get; } = new ObservableCollection<string>(); public void StartServer() { pServer = new Process(); pServer.StartInfo.FileName = "java"; pServer.StartInfo.Arguments = @"-jar " + "-Xms512M -Xmx1G spigot.jar"; pServer.StartInfo.UseShellExecute = false; pServer.StartInfo.RedirectStandardOutput = true; pServer.StartInfo.RedirectStandardError = true; pServer.StartInfo.RedirectStandardInput = true; pServer.OutputDataReceived += OKDataReceived; pServer.ErrorDataReceived += ErrorDataReceived; pServer.Start(); pServer.BeginErrorReadLine(); pServer.BeginOutputReadLine(); } private void ErrorDataReceived(object sender, DataReceivedEventArgs e) => Application.Current.Dispatcher.Invoke(() => ConsoleLines.Add($"ERROR: {e.Data}")); private void OKDataReceived(object sender, DataReceivedEventArgs e) => Application.Current.Dispatcher.Invoke(() => ConsoleLines.Add($"MESSAGE: {e.Data}"));據我所知,一切都設置正確,我看不出任何錯誤。
1 回答

白豬掌柜的
TA貢獻1893條經驗 獲得超10個贊
您應該Server從 MainWindow 中刪除該字段并啟動 DataContext 中的服務器。
private void BtnStart_OnClick(object sender, RoutedEventArgs e)
{
((MasterViewModel)DataContext).Server.StartServer();
}
或者,像這樣初始化視圖模型:
DataContext = new MasterViewModel { Server = Server };
它將 Server 字段值分配給視圖模型中的 Server 屬性(然后必須是讀/寫)。否則,您將有兩個 Server 實例。
- 1 回答
- 0 關注
- 277 瀏覽
添加回答
舉報
0/150
提交
取消