【问题标题】:Multiple ViewModel : Pass event to other ViewModel多个 ViewModel :将事件传递给其他 ViewModel
【发布时间】:2015-01-31 07:14:30
【问题描述】:

我在ShellView 中有一个Button 我希望这个按钮被触发到FooViewModel 但不起作用,任何想法。

<Window x:Class="CM.Views.ShellView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">

<Button cal:Message.Attach="[Event Click]=[Action FooViewModel.About]"/>
</Window>


namespace CM.ViewModels
 {
    public class ShellViewModel : Conductor<IScreen>.Collection.OneActive, IShellViewModel
    {
        public ShellViewModel()
        {
        }
   }

   public class FooViewModel
   {
         public void About()
         {
             MessageBox.Show("About method fired");
         }
   }
}

【问题讨论】:

  • 我认为 viewmodel 为视图呈现数据和命令。但在这种情况下,您想为另一个视图中的按钮触发命令。你不认为它打破了对 mvvm 的看法吗:?

标签: c# wpf mvvm caliburn.micro


【解决方案1】:

Caliburn.Micro 有 Event Aggregator 用于在视图模型之间传递消息。

在这种情况下,您可以向ShellViewModel 添加按钮调用的方法。这会在FooViewModel 可以侦听的事件聚合器上发布一条消息。

【讨论】:

    【解决方案2】:

    【讨论】:

    • 啊,对不起,我自己不使用那个。我可能会看看 codeplex.com 上 Caliburn.Micro 文档中的“事件聚合器”。
    【解决方案3】:

    我发现一个解决方案效果很好,但可能不是正确的方法。如果不是正确的方法指导大师。

        //Register with Windsor
        public class ViewInstaller : IWindsorInstaller
        {
            public void Install(IWindsorContainer container, IConfigurationStore store)
            {
                container.Register(Component.For<IShellViewModel>().ImplementedBy<ShellViewModel>().LifestyleSingleton());
                container.Register(Component.For<IFooViewModel >().ImplementedBy<FooViewModel>().LifestyleSingleton());
            }
        }
    
    <Window x:Class="CM.Views.ShellView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
    
    <Button cal:Message.Attach="[Event Click]=[Action About]" cal:Action.Target="CM.ViewModels.FooViewModel"/>
    </Window>
    
    namespace CM.ViewModels
     {
        public class ShellViewModel : Conductor<IScreen>.Collection.OneActive, IShellViewModel
        {
            public ShellViewModel()
            {
            }
       }
    
       public class FooViewModel : IFooViewModel
       {
             public void About()
             {
                 MessageBox.Show("About method fired");
             }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-19
      相关资源
      最近更新 更多