【问题标题】:UWP - Update TCP-Connection-Status from another Thread in TextBoxUWP - 从 TextBox 中的另一个线程更新 TCP 连接状态
【发布时间】:2017-04-20 10:23:31
【问题描述】:

我的 TCP 连接有以下代码。我不知道它是否正确异步运行,所以我添加了 Task.Delay(1000) 以便让方法接收结果,将其保存到“结果”,然后将其提供给 UI。

我的问题是,如何将字符串“结果”绑定到我的文本框。一旦“结果”从 Connect(...) 方法获得结果,我希望文本框在 UI 线程中刷新。

public static async Task Connect(string ip, int port) {

            result = string.Empty;

            DnsEndPoint hostEntry = new DnsEndPoint(ip, port);


            Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = hostEntry;


            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
            {

                result = e.SocketError.ToString();    
            });


           _socket.ConnectAsync(socketEventArg);
            await Task.Delay(1000); 

        }

XAML 代码隐藏

            await TCPConnection.Connect(_con.IpAddress,port);
            tbConnectionText.Text = "Connectionstatus: " + _con.IpAddress;
            tbConnectionStatus.Text =TCPConnection.result;
            tbConnectionText.Visibility = Visibility.Visible;
            tbConnectionStatus.Visibility=Visibility.Visible;

【问题讨论】:

    标签: c# textbox uwp task observable


    【解决方案1】:

    您可以编写绑定并使用 NotifyProperty 更改 TextBox。

    在 ViewModel 中写入 Result 字符串,任务结束时将更改它。

    ViewModel 应该继承 NotifyProperty 并且属性在集合中使用 OnPropertyChanged。

    public string Result 
    {
        set
        {
             _result=value;
             OnPropertyChanged(); 
        }
        get
        {
             return _result;
        }
    }
    
      public static async Task Connect(string ip, int port)
      {
    
            result = string.Empty;
    
            DnsEndPoint hostEntry = new DnsEndPoint(ip, port);
    
    
            Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
    
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = hostEntry;
    
    
            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate (object s, SocketAsyncEventArgs e)
            {
    
                result = e.SocketError.ToString();    
            });
    
    
           _socket.ConnectAsync(socketEventArg);
            await Task.Delay(1000); 
            Result=TCPConnection.result;
        }
    

    可以绑定文本框

            Binding bind=new Binding()
            {
                 Path = new PropertyPath("Result"),
            };
            bind.Source = ViewModel;
            bind.Mode=BindingMode.OneWay;
            BindingOperations.SetBinding(TextBox,TextBox.TextProperty, bind);
    

    如果你只使用 Main.xaml.cs

    你也可以在 Main() 中使用 bind;

            Binding bind=new Binding("Result");
            bind.Source = this;
            bind.Mode=BindingMode.OneWay;
            BindingOperations.SetBinding(TextBox,TextBox.TextProperty, bind);
    

    你应该让 Main 继承 INotifyPropertyChanged

    你应该在你的代码中写下跟随

    public event PropertyChangedEventHandler PropertyChanged;
    
        public void UpdateProper<T>(ref T properValue, T newValue, [CallerMemberName] string properName = "")
        {
            if (Equals(properValue, newValue))
            {
                return;
            }
    
            properValue = newValue;
            OnPropertyChanged(properName);
        }
    
        public async void OnPropertyChanged([CallerMemberName] string name = "")
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                () => { handler?.Invoke(this, new PropertyChangedEventArgs(name)); });
        }
    

    【讨论】:

    • 但我没有 ViewModel。我只有 tcp 类和 mainpage.xaml.cs
    • public MainPage() { InitializeComponent(); btnBroadcast_pressed = false; Binding bind = new Binding(); bind.Source = TCPConnection.result; bind.Mode = BindingMode.OneWay; BindingOperations.SetBinding(tbConnectionStatus, TextBox.TextProperty, bind); } 最后一个函数抛出 Access.Violation.Exception
    • @David 什么是 tbConnectionStatus?在xml中?
    • 我想绑定到字符串的文本框导致我的 tcp 类。此外,new Binding("Result") 不起作用,因为没有带 1 个参数的构造函数。
    猜你喜欢
    • 1970-01-01
    • 2012-02-08
    • 2012-04-27
    • 1970-01-01
    • 2013-06-28
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多