亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的 ObservableCollection 不更新我的 UI?

為什么我的 ObservableCollection 不更新我的 UI?

C#
料青山看我應如是 2021-06-16 17:35:44
我很確定我錯過了一些非常小的東西,但我一生都無法弄清楚我哪里出錯了。我試圖將我的數據網格綁定到實際上正在獲取輸入的 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 實例。


查看完整回答
反對 回復 2021-06-20
  • 1 回答
  • 0 關注
  • 277 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號