如何从另一个页面调用MainWindows上的方法

时间:2015-03-18 11:12:53

标签: c# wpf xaml methods non-static

我有MainWindow.xaml和另一个Page.xaml在同一个命名空间

在MainWindow上是文本块和框架。

MainWindow上的框架显示Page.xaml和该页面上的一个按钮。

我想在MainWindow中使用该Button调用非静态方法,但我不知道如何:(

例如:

MainWindow.xaml.cs

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

        private void openframe()
        {
            frame1.Source = new Uri("testapge.xaml", UriKind.Relative);

        }
        public void MyMethod()
        {
            textblock1.Text = "This text is showed on MainWindow if i click to the Button";
        }    
    }
}

Page.xaml.cs

    namespace wpfapp
{
    public partial class Page : Page
    {
        public Page()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MainWindow trytocallit = new MainWindow();
            trytocallit.MyMethod();
        }
    }
}

这当然不起作用。谢谢你的帮助!

5 个答案:

答案 0 :(得分:2)

你可以做几件不同的事情。您可以实现Muds' answer之类的内容,类似于Singleton pattern

另一种方法是使用dependency injectionPage类创建MainWindow个实例。

public class Page : Page
{
  private MainWindow MainWindow;

  public Page(MainWindow mainWindow)
  {
    InitializeComponent();

    this.MainWindow = mainWindow;

    // Other constructor stuff
  } 

  // Other methods, event handlers, etc.
}

通常使用依赖注入,我们依赖于抽象而不是具体实现(以减少耦合)。

public interface IMainWindowThatDoesSomething
{
  void DoSomething();
}

public class MainWindow : Window, IMainWindowThatDoesSomething
{
  // Constructor, methods, event handlers, etc. go here.

  public void DoSomething()
  {
    // Implementation here.
  } 
}

public class Page : Page
{    
  private IMainWindowThatDoesSomething mainWindow;

  public Page(IMainWindowThatDoesSomething mainWindow)
  {
    InitializeComponent();

    this.mainWindow = mainWindow;

    // Other constructor jazz.
  }

  private void UserDidSomethingAndMainWindowNeedsToReact()
  {
    mainWindow.DoSomething();
  }
}

答案 1 :(得分:1)

作为替代和快速解决方案,您可以使用以下代码

用法:

   MainWindow mainWindow = GetMainWindow();

方法:

    public static MainWindow GetMainWindow() 
    {
        MainWindow mainWindow=null;

        foreach (Window window in Application.Current.Windows)
        {
            Type type = typeof(MainWindow);
            if (window != null && window.DependencyObjectType.Name == type.Name)
            {
                 mainWindow = (MainWindow)window;
                if (mainWindow != null)
                {
                    break;
                }
            }
        }


        return mainWindow;

    }

答案 2 :(得分:0)

这样做听起来不对,但如果你必须在内存中获取对象而不是创建一个新对象..

但是这个声音听起来没错..告诉我们你为什么要这样做,以便我们能提出更好的方法

---只是为了让你的案子有效..做这个..

在主窗口中 -

public static MainWindow Instance { get; private set; }

    static MainWindow()
{
    Instance = new MainWindow();
}

private MainWindow()
{
    InitializeComponent();
}

在app.xaml中删除StartupUri =“MainWindow.xaml”

public App()
{
    Startup += App_Startup;        
}

void App_Startup(object sender, StartupEventArgs e)
{
    TestApp.MainWindow.Instance.Show();
}

现在,您可以访问

上的静态实例...调用方法

答案 3 :(得分:0)

考虑利用带参数的消息传递来在对象之间传递数据。

您可以使用EventAggregatorMessageBus

我们的想法是让您的用户控件订阅他们想要响应的事件。

注:

我使用viewmodels执行此操作。 但是,我认为将此代码添加到用户控件时会出现代码异味,无论使用它们的应用程序如何,这些代码都是通用的。

我使用 发布订阅模式 来处理复杂的类依赖项:

<强>视图模型:

    public class ViewModel : ViewModelBase
    {
        public ViewModel()
        {
            CloseComand = new DelegateCommand((obj) =>
                {
                    MessageBus.Instance.Publish(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, null);
                });
        }
}

<强>窗口:

public partial class SomeWindow : Window
{
    Subscription _subscription = new Subscription();

    public SomeWindow()
    {
        InitializeComponent();

        _subscription.Subscribe(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, obj =>
            {
                this.Close();
            });
    }
}

您可以利用Bizmonger.Patterns获取MessageBus。

<强> MessageBus

public class MessageBus
{
    #region Singleton
    static MessageBus _messageBus = null;
    private MessageBus() { }

    public static MessageBus Instance
    {
        get
        {
            if (_messageBus == null)
            {
                _messageBus = new MessageBus();
            }

            return _messageBus;
        }
    }
    #endregion

    #region Members
    List<Observer> _observers = new List<Observer>();
    List<Observer> _oneTimeObservers = new List<Observer>();
    List<Observer> _waitingSubscribers = new List<Observer>();
    List<Observer> _waitingUnsubscribers = new List<Observer>();

    int _publishingCount = 0;
    #endregion

    public void Subscribe(string message, Action<object> response)
    {
        Subscribe(message, response, _observers);
    }

    public void SubscribeFirstPublication(string message, Action<object> response)
    {
        Subscribe(message, response, _oneTimeObservers);
    }

    public int Unsubscribe(string message, Action<object> response)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Respond == response).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Respond == response));
        observers.AddRange(_oneTimeObservers.Where(o => o.Respond == response));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public int Unsubscribe(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription).ToList());
        observers.AddRange(_waitingSubscribers.Where(o => o.Subscription == subscription));
        observers.AddRange(_oneTimeObservers.Where(o => o.Subscription == subscription));

        if (_publishingCount == 0)
        {
            observers.ForEach(o => _observers.Remove(o));
        }

        else
        {
            _waitingUnsubscribers.AddRange(observers);
        }

        return observers.Count;
    }

    public void Publish(string message, object payload)
    {
        _publishingCount++;

        Publish(_observers, message, payload);
        Publish(_oneTimeObservers, message, payload);
        Publish(_waitingSubscribers, message, payload);

        _oneTimeObservers.RemoveAll(o => o.Subscription == message);
        _waitingUnsubscribers.Clear();

        _publishingCount--;
    }

    private void Publish(List<Observer> observers, string message, object payload)
    {
        Debug.Assert(_publishingCount >= 0);

        var subscribers = observers.Where(o => o.Subscription.ToLower() == message.ToLower());

        foreach (var subscriber in subscribers)
        {
            subscriber.Respond(payload);
        }
    }

    public IEnumerable<Observer> GetObservers(string subscription)
    {
        var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription));
        return observers;
    }

    public void Clear()
    {
        _observers.Clear();
        _oneTimeObservers.Clear();
    }

    #region Helpers
    private void Subscribe(string message, Action<object> response, List<Observer> observers)
    {
        Debug.Assert(_publishingCount >= 0);

        var observer = new Observer() { Subscription = message, Respond = response };

        if (_publishingCount == 0)
        {
            observers.Add(observer);
        }
        else
        {
            _waitingSubscribers.Add(observer);
        }
    }
    #endregion
}

}

<强>订阅

public class Subscription
{
    #region Members
    List<Observer> _observerList = new List<Observer>();
    #endregion

    public void Unsubscribe(string subscription)
    {
        var observers = _observerList.Where(o => o.Subscription == subscription);

        foreach (var observer in observers)
        {
            MessageBus.Instance.Unsubscribe(observer.Subscription, observer.Respond);
        }

        _observerList.Where(o => o.Subscription == subscription).ToList().ForEach(o => _observerList.Remove(o));
    }

    public void Subscribe(string subscription, Action<object> response)
    {
        MessageBus.Instance.Subscribe(subscription, response);
        _observerList.Add(new Observer() { Subscription = subscription, Respond = response });
    }

    public void SubscribeFirstPublication(string subscription, Action<object> response)
    {
        MessageBus.Instance.SubscribeFirstPublication(subscription, response);
    }
}

答案 4 :(得分:0)

抱歉迟到的回复,我有一个简单的决议。

  • 在Page.xaml中创建公共字符串变量。
  • 如果单击页面上的按钮,变量将获得一些值。
  • 在MainWindow上创建新的背景,然后运行无限循环(true){..}
  • 使用Thread.Sleep(10);
  • 一次又一次地循环控制值public字符串变量
  • 如果找到在MainWindow中执行某项操作的值

它对我来说也很简单:)