代码之家  ›  专栏  ›  技术社区  ›  msfanboy

使用MVVM模式处理控件上的鼠标事件-最佳实践-

  •  5
  • msfanboy  · 技术社区  · 16 年前

    实际上,我找到了两种方法来处理mvvm模式控件上的鼠标事件。

    MVVM Light工具箱 http://mvvmlight.codeplex.com/

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SelectionChanged">
            <cmd:EventToCommand
                Command="{Binding SelectionChangedCommand}"
                CommandParameter="{Binding SelectedItems,
                    ElementName=MyDataGrid}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    

    以及将interactivity.dll与行为

    <i:Interaction.Triggers>
      <i:EventTrigger EventName=”MouseLeftButtonDown”>
        <Behaviours:ExecuteCommandAction Command=”{Binding MyCommand}” CommandParameter=”{Binding MyCommandParameter}”/>
      </i:EventTrigger>
    </i:Interaction.Triggers>
    

    主持人:为什么我的最后6行xaml代码根本看不见? 它们被IE和铁浏览器吞没了。 请你报告管理员来修改代码脚本好吗?它一点也不常起作用。证明: http://img251.imageshack.us/img251/5236/errorxt.png

    3 回复  |  直到 16 年前
        1
  •  7
  •   Ray Burns    16 年前

    如果您需要在任意位置处理MouseDown,那么这两种方法都是很好的方法。

    然而,这些情况一般很少。通常有一种更简单的方法:

    • 您确定您的对象只是列表中对象的选择区域吗?如果是这样,请将容器从ItemsControl更改为ListBox,并重新设置ListBoxItem的样式以使用选择区域。
    • 您的对象是正在选择的图形路径吗?使用内容为路径本身的ToggleButton。

    这方面还有很多其他的例子。事实上,很少会发现MouseDown映射到一个命令,并且没有一种更干净的方法来做同样的事情。

        2
  •  6
  •   jbe    16 年前

    总有另一种选择。您可以在视图的代码隐藏中处理WPF事件,并对ViewModel调用适当的方法。MVVM模式并不禁止在视图的代码隐藏文件中编写任何代码。

    这个 应用程序示例 WPF Application Framework (WAF) 显示了如何工作。

        3
  •  1
  •   user3537866 user3537866    12 年前

    XCommand开源codeplex项目有更好的方法来处理这种基于事件的命令/命令参数绑定。在这里找到, xcommand.codeplex.com

    <Grid>
        <TextBlock Margin="20,30,20,0" VerticalAlignment="Top" Height="80" x:Name="XTextBlock"
               Foreground="{Binding FgColor, Mode=TwoWay}"
               XCmd:MouseMove.Command="{Binding TextBlockPointerMovedCommand}"
               XCmd:MouseLeftButtonDown.Command="{Binding TextBlockPointerPressedCommand}"
               XCmd:MouseLeave.Command="{Binding TextBlockPointerExitedCommand}"    
               Text="{Binding Description, Mode=TwoWay}">
        </TextBlock>
        <Grid Grid.Column="1" Background="{Binding BgColor, Mode=TwoWay}"
              XCmd:MouseMove.Command="{Binding GridPointerMovedCommand}" 
              XCmd:MouseMove.CommandParameter="{Binding ElementName=XTextBlock, Path=Text}"
              XCmd:MouseLeftButtonDown.Command="{Binding GridPointerPressedCommand}"
              XCmd:MouseLeftButtonDown.CommandParameter="{Binding ElementName=XTextBlock, Path=Text}"
              >
        </Grid>
    </Grid>
    

    推荐文章