获取不是MainWindow WPF的窗口

时间:2015-11-25 07:10:25

标签: c# .net wpf wcf xaml

我想从我的WPF应用程序中不是MainWindow的窗口的代码隐藏中调用该方法,像我一样转换窗口类型。

ClientCallBack.cs:

string s1 = "let's play football";
string s2 = "let's paly fotbal and cricket";

if (s1 != s2)
{
    var str1Parts = s1.Split(' ');
    var str2Parts = s2.Split(' ');

    var wrongOrExtraWords = str2Parts.Where(s => !str1Parts.Contains(s)).ToList();

    Console.WriteLine("Wrong words: ({0})", wrongOrExtraWords.Count());

    foreach (var str2 in wrongOrExtraWords)
    {
        Console.WriteLine(str2);
    }
}
else
{
    Console.WriteLine("Both strings are equal.");
}

ChatWPFClient.xaml.cs:

using ChattingInterfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace ChatClient
{
    [CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class ClientCallback : IClient
    {
        public void GetMessage(string message, string userName)
        {
            //get casted instance of chat client window (NOT MainWindow!)
        }
    }
}

如何在其他类中调用此方法的TakeMessage,以便我可以使用该代码隐藏窗口填充ChatWPFClient.xaml的XAML文件?提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先创建一个可以传递给ClientCallback的接口

public interface IMessageHandler
{
    void TakeMessage(string message, string userName);
}

然后在ClientCallBack中将接口作为构造函数中的参数。

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class ClientCallback : IClient
{
    private IMessageHandler messageHandler;

    public ClientCallBack(IMessageHandler messageHandler)
    {
        this.messageHandler = messageHandler;
    }

    public void GetMessage(string message, string userName)
    {
        messageHandler.TakeMessage(message, userName);
    }
} 

使用ChatWpfClient的接口并在构造函数中传递实例。

public partial class ChatWPFClient : Window, IMessageHandler
{
    ... 

    public ChatWPFClient()
    {
        InitializeComponent();
        _channelFactory = new DuplexChannelFactory<IChattingService>(new ClientCallback(this), "ChattingServiceEndpoint");
        Server = _channelFactory.CreateChannel();

    }

    ...

    // This is a part of the interface now and needs to be implemented here
    public void TakeMessage(string message, string userName) 
    {
        chatBox.Text += userName + ": " + message + "\n";
    }
}

此外,您可以在ChatWPFClient类上实现IClient并使用CallBackBehavior属性进行修饰,并将其自身作为回调传递。但是不要认为这是推荐的,看起来很奇怪。

_channelFactory = new DuplexChannelFactory<IChattingService>(this, "ChattingServiceEndpoint");