XAML C#跨多个窗口的功能

时间:2011-09-08 14:01:49

标签: c# wpf events xaml

我有一个我正在研究的程序,它有多个窗口。窗口的功能类似,我希望有一个事件处理程序来覆盖应用程序中每个窗口的按钮事件。这可能吗?

2 个答案:

答案 0 :(得分:1)

如果你需要在代码中绑定一个处理程序,你可以通过委托封装处理程序并注入到需要它的Windows中。

例如使用Action<T>

Action<string> commonHandler = (parameter) => 
   { 
         // handler code here 
   };


class MyWindiow
{

   public MyWindiow(Action<string> handler)
   { 
         // store to local and assign to button click
         // button.CLick += (o, e) => { handler(parameterToBepassed); }
   }
}

答案 1 :(得分:0)

我会考虑使用框架来帮助你。我最喜欢的是Prism v4

如果你遵循M-V-VM设计模式,你的生活将变得更加轻松。您需要了解Data Binding and DataContext


话虽如此,如果您决定走这条路,您可以将每个窗口绑定到一个命令:

<Button Command="{Binding DoFooCommand}" Content="DoFoo"/>

你的ViewModel会有一个DelegateCommand成员来执行。

public class SomeViewModel : NotificationObject
{
    public SomeViewModel()
    {
        DoFooCommand = new DelegateCommand(ExecuteFoo);
    }

    public DelegateCommand DoFooCommand { get; set; }

    private void ExecuteFoo()
    {
        //Use the EventAggregator to publish a common event
    }
}

最后,在您的解决方案的其他地方,您将拥有一个订阅该事件的代码文件/类,并等待某人发布该事件以进行处理。

public class SomeOtherPlace
{
    public SomeOtherPlace()
    {
        //Use the EventAggregator to subscribe to the common event
    }

    public void FooBarMethodToCallWhenEventIsPublished(SomePayload payload)
    {
        //Do whatever you need to do here...
    }
}

我意识到有些事情被遗漏了(例如“SomePayload”是什么......查看EventAggregator信息),但我不想太过分了。只需向您提供一个指导信息,以及可以使用的基本代码。如果您决定使用EventAggregator,那么您需要确保您的订阅呼叫和发布呼叫正在使用EventAggregator的SAME实例。您可以通过查看MEF来完成此操作。棱镜设置与MEF完美配合......我不会撒谎。完成所有这些工作需要一些学习曲线,但最终您可以轻松地对ViewModel进行单元测试并使代码松散耦合。 EventAggregator是一种很好的方式,可以让不同的类在不依赖于彼此了解的情况下相互通信。 MEF非常适合您希望在整个应用程序中使用的Container服务。

希望能让您对如何在正确的道路上做您想做的事情有所了解。