【问题标题】:"Bubbling" events from bound viewmodel goes to parent来自绑定视图模型的“冒泡”事件转到父级
【发布时间】:2014-07-18 13:02:57
【问题描述】:

首先,我仍然习惯于 Caliburn 和 WPF,所以我可能以错误的方式执行此操作。我很想知道更好的方法!

我有一个Conductor shell 视图模型,它有一个包含一些共享元素的视图,以及一个ActiveItem 的内容控件。现在,我希望将来自ActiveItem 视图模型的一组按钮显示在内容控件之外,但仍然让它们的点击事件转到活动视图模型。我试过像这样添加ItemsControl

    <ItemsControl x:Name="ActiveItem_Buttons">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" HorizontalAlignment="Right"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Name}" Margin="10" Height="25" Width="80">
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="Click">
                            <cal:ActionMessage MethodName="{Binding Name}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

(我正在做 Interaction.Trigger 部分,因为我无法绑定到 x:Name,这会导致 Caliburn 自动连接它)

但是,我收到一个异常,指出 Caliburn 找不到匹配的方法。似乎它开始从 shell 视图模型而不是活动项目视图模型中冒泡事件。如何设置事件冒泡的“起点”?我找到并尝试了附加属性cal:View.Model="{Binding ActiveItem}",但这似乎没有帮助。

编辑:为了清楚起见:Buttons 属性定义在视图模型基类 ButtonScreenBase 上,shell 继承 Conductor&lt;ButtonScreenBase&gt;

【问题讨论】:

    标签: c# wpf caliburn.micro


    【解决方案1】:

    不要在 WPF 中使用事件和事件处理,尤其是与 MVVM 结合使用时。请改用Command 模式。对于用户操作,这意味着您可以通过 View 中的手势、点击和其他类型的用户交互事件触发命令,并在 ViewModel 中从 View 触发的 Command 类/方法中包含业务逻辑,从而保持分离用户界面逻辑和业务逻辑。

    我推荐这个链接来了解命令以及如何实现它们(以及从基本原理中实现的 MVVM):http://kentb.blogspot.co.uk/2009/04/mvvm-infrastructure-delegatecommand.html

    【讨论】:

      【解决方案2】:

      更新:回去查看有关此特定问题的其他一些帖子,该人本人对此问题的解释。

      Bind a Command to a Button inside a ListView with Caliburn.Micro

       <Button Content="{Binding Name}" cal:Bind="{Binding}" Margin="10" Height="25" Width="80">
           <i:Interaction.Triggers>
               <i:EventTrigger EventName="Click">
                   <cal:ActionMessage MethodName="{Binding Name}" />
                </i:EventTrigger>
           </i:Interaction.Triggers>
      </Button>
      

      同样是数据模板的继承问题。

      【讨论】:

        猜你喜欢
        • 2021-09-05
        • 1970-01-01
        • 1970-01-01
        • 2010-12-07
        • 2015-09-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多