Send information between 2 wpf windows

陌路散爱 提交于 2019-12-12 04:16:58

问题


We have 2 windows open, like a chat

This is what the textBox and the button looks like:

private void textBox_chat_TextChanged(object sender, TextChangedEventArgs e)
{
}

private void button_enviar_Click(object sender, RoutedEventArgs e)
{
    string chatMessage = textBox_chat.Text;
}

I would like to know how can I send information insered in a textbox by pressing the button "button_enviar". And to be printed to the other window. I have been looking things like Application.Current.Windows... but still don't found the way to make it.

My code looks actually like this:

MainWindow

   namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
            }

            // automatic code generated by the button
            private void button_entrar_Click(object sender, RoutedEventArgs e)
            {
                // we catch the taxt input in the texBox
                string userLoginName = textBox_pantalla_inicial.Text;

                // We call the chat window
                Window window1 = new Window1();
                // we put the user name as the title of the chat window
                window1.Title = userLoginName;
                // show the chat window
                window1.Show();            
            }       
        }
    }

ChatWindow

namespace WpfApplication1
{
    /// <summary>
    /// Lógica de interacción para Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            // inicialize chatWindow
            InitializeComponent();            
        }

        private void textBox_chat_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void button_enviar_Click(object sender, RoutedEventArgs e)
        {
            string chatMessage = textBox_chat.Text;

        }       

        private void button_erase_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}

回答1:


First, you should look into binding with XAML, such as here. That way in your C# code, you won't need to care about the UI controls used--and you can easily change those controls in the XAML if you don't like something or want to improve your window.

You only need to think of your MainWindow and ChatWindow as objects. There are many ways you can make this work. One of the simplest ways is to have an event in your chat window that your main window subscribes to when it creates the chat window. Whenever a user enters his message, the chat window raises the event and passes the text through arguments in the event, which the main window catches and then can call a method (or set a property) in all the chat windows it is tracking so that the message gets passed to all chat windows.

A simple example (free-typed, not tested):

public class MainWindow : Window
{
    List<ChatWindow> chatWindows = new List<ChatWindow>();
    public void AddChatWindow()
    {
        ChatWindow win = new ChatWindow();
        win.NewMessage += MessageReceived;
        win.Show();
        chatWindows.Add(win);
    }
    void MessageReceived(object sender, MessageEventArgs e)
    {
        ChatWindow me = sender as ChatWindow;
        if (me != null)
        {
            foreach (ChatWindow win in chatWindows)
            {
                if (win != me)
                {
                    win.Add(e.Message);
                }
            }
        }
    }
}

public class ChatWindow : Window
{
    public event EventHandler<MessageEventArgs> NewMessage;

    public void Add(string message)
    {
        Messsage += message;
    }
    public void UpdateText(string text)
    {
        if (NewMessage != null)
        {
            NewMessage(this, new MessageEventArgs(Message = text));
        }
    }
    public string Message {get;set;}
}
public class MessageEventArgs : EventArgs
{
     public string Message{get;set;}
}



回答2:


This is how I would do :

public partial class ChatWindow : Window
{

    private Client client;
    public ChatWindow(Client _client)
    {
        InitializeComponent();
        client = _client;
        this.Title = client.Name + " chat";
        client.MessageReceived += OnMessageReceived;


        this.Loaded += OnLoaded;
    }

    public void OnMessageReceived(object sender, MessageReceivedArgs e)
    {
        chatControl.Text += e.Sender.Name+": "+ e.Message;
    }

    private void OnLoaded(object sender, EventArgs e)
    {
        client.Send("client " + client.Name + " is loaded!");
    }


}


public class Client{

    public string Name { get; set; }
    public Chat chat{get;set;}



    public Client(string name)
    {
        Name = name;
    }

    public delegate void MessageReceivedEventHandler(object sender, MessageReceivedArgs e);

    public event MessageReceivedEventHandler MessageReceived;

    private void RaiseMessageReceivedEvent(Client sender, string message)
    {
        MessageReceivedArgs e = new MessageReceivedArgs(sender,message);
        if (MessageReceived != null)
            MessageReceived(this, e);
    }

    public void MessageReceivedFromChat(Client sender,string message)
    {
        RaiseMessageReceivedEvent(sender,message);
    }

    public void Send(string message)
    {
        chat.SendMessage(this, message);
    }




}

public class MessageReceivedArgs : EventArgs
{
    public string Message { get; set; }
    public Client Sender { get; set; }
    public MessageReceivedArgs(Client sender,string message)
    {
        Message = message;
        Sender = sender;
    }
}


public class Chat
{
    private List<Client> clients;

    public Chat()
    {
        clients = new List<Client>();
    }

    public void AddClient(Client client)
    {
        client.chat = this;
        clients.Add(client);
    }

    public void RemoveClient(Client client)
    {
        client.chat = null;
        clients.Remove(client);
    }

    public void SendMessage(Client sender, string message)
    {
        foreach(Client client in clients){
            if (client != sender)
            {
                client.MessageReceivedFromChat(sender, message);
            }

        }
    }

}

Create objects :

        Chat chat = new Chat();
        Client jacques = new Client("jacques");
        Client Pierre = new Client("Pierre");
        chat.AddClient(jacques);
        chat.AddClient(Pierre);

        ChatWindow cw = new ChatWindow(jacques);
        cw.Show();
        ChatWindow cw1 = new ChatWindow(Pierre);
        cw1.Show();



回答3:


I set a little example code that used an event:

    public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    ChatMsgDispacher _chatMsgDispacher = new ChatMsgDispacher();
    public ChatChild GetNewChat()
    {
        var child = new ChatChild(); //or where you create the child
        child.SetMsgDispacher(_chatMsgDispacher);
        return child;
    }
}

public class ChatMsgDispacher
{
    public delegate void ChatMsgDelegate(string msg);
    public event ChatMsgDelegate MessageUpdate;

    public void Update(string msg)
    {
        if (MessageUpdate != null)
        {
            MessageUpdate(msg);
        }
    }
}


public class ChatChild
{
    private ChatMsgDispacher _msgDispacher;

    public void SetMsgDispacher(ChatMsgDispacher msgDispacher)
    {
        _msgDispacher = msgDispacher;
        _msgDispacher.MessageUpdate += MsgDispacher_MessageUpdate;
    }

    void MsgDispacher_MessageUpdate(string msg)
    {
        //add the msg in the child view
    }

    private void button_enviar_Click(object sender, RoutedEventArgs e)
    {
        string chatMessage = textBox_chat.Text;
        _msgDispacher.Update(chatMessage);
    }
}


来源:https://stackoverflow.com/questions/34047083/send-information-between-2-wpf-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!