0

在我开始之前,这里有一点背景。我开始在 WPF 中创建我的应用程序,就像在 WinForms 中编程一样。显然,这完全是在绕过WPF的强大。所以现在我已经阅读了有关 WPF 和 MVVM 框架的更多信息,我开始调整我的应用程序以在模型 - 视图 - 视图模型方式下工作。

之前,我曾经在我的 Window 中有代码隐藏,只是处理了 MouseDown RoutedEvents,然后继续并提示一个窗口进行签名。我的 DockPanel 和 Image 似乎没有Command.

我怎样才能以 MVVM 的方式做到这一点?RoutedEvents 是解决这种情况的方法吗?

4

3 回答 3

9

不要用行为和其他东西使整个事情复杂化,而是将所有 UI 元素放在按钮的 ControlTemplate 中并使用它的命令:

<Button Command="{Binding YourCommand}">
   <Button.Template>
      <ControlTemplate TargetType="Button">
          <DockPanel>
             <Image/>
             <!-- Whatever -->
          </DockPanel>
      </ControlTemplate>
   </Button.Template>
</Button>
于 2013-11-05T19:47:59.517 回答
3

您可以使用Blend SDK附带的交互触发器。

步骤-

  • 添加对 assembly 的引用System.Windows.Interactivity

  • 在 XAML 文件中添加相应的命名空间

    xmlns:interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

您可以像示例一样使用它 -

<StackPanel>
   <interactivity:Interaction.Triggers>
      <interactivity:EventTrigger EventName="MouseDown">
        <interactivity:InvokeCommandAction Command="{Binding CloseCommand}"/>
      </interactivity:EventTrigger>
   </interactivity:Interaction.Triggers>            
</StackPanel>

CloseCommand 在您的 ViewModel 类中。

于 2013-11-05T18:49:56.207 回答
1

实施图片点击:

  1. 编写一个扩展System.Windows.Control.Image的类。
  2. 创建一个RoutedEventRoutedEventHandler,方便鼠标点击事件。
  3. 覆盖OnMouseLeftButtonDown

在我的示例中,我评估了点击次数,因为不知道如何更好地做到这一点

public class ImageHelper : Image
    {
        public static readonly RoutedEvent MouseLeftButtonClick =
            EventManager.RegisterRoutedEvent(
                "MouseLeftButtonClick",
                RoutingStrategy.Bubble,
                typeof(RoutedEventHandler),
                typeof(ImageHelper));

        public event RoutedEventHandler MouseLeftButtonClickEvent
        {
            add
            {
                AddHandler(MouseLeftButtonClick, value);
            }
            remove
            {
                RemoveHandler(MouseLeftButtonClick, value);
            }
        }

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            if (e.ClickCount == 1)
            {
                RaiseEvent(new MouseLeftButtonClickEventArgs(
                    MouseLeftButtonClick, this));
            }
            base.OnMouseLeftButtonDown(e);
        }

        public class MouseLeftButtonClickEventArgs : RoutedEventArgs
        {
            public MouseLeftButtonClickEventArgs(RoutedEvent routedEvent, object source)
                : base(routedEvent, source)
            {
               // some code.....
            }
        }
    }

XAML:

<local:ImageHelper>
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="MouseLeftButtonClickEvent">
                    <i:InvokeCommandAction Command="{Binding Path=MyCommand}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
 </local:ImageHelper>
于 2013-11-05T19:11:20.080 回答