如何将作物编码从代码后台迁移到视图模型wpf

时间:2015-03-02 12:53:59

标签: c# wpf xaml mvvm

成为WPF和MVVM的新手,我到处搜索,找到了解决问题的好方法。我正在创建裁剪应用程序,但我尝试将代码后面的代码迁移到视图模型。我能够通过使用混合交互触发器代码来绑定我的鼠标按钮事件:

    <Grid x:Name="GridLoadedImage" HorizontalAlignment="Left" VerticalAlignment="Top">
                <i:Interaction.Triggers>
                    <i:EventTrigger EventName="MouseLeftButtonDown">
                        <i:InvokeCommandAction Command="{Binding MouseLeftButtonDownCommand}"/>
                    </i:EventTrigger>
                    <i:EventTrigger EventName="MouseLeftButtonUp">
                        <i:InvokeCommandAction Command="{Binding MouseLeftButtonUpCommand}"/>
                    </i:EventTrigger>
                    <i:EventTrigger EventName="MouseMove">
                        <i:InvokeCommandAction Command="{Binding MouseMoveCommand}"/>
                    </i:EventTrigger>
                </i:Interaction.Triggers>
                <Grid.LayoutTransform>
                    <ScaleTransform ScaleX="{Binding ElementName=slider1, Path=Value}" ScaleY="{Binding ElementName=slider1, Path=Value}"/>
                </Grid.LayoutTransform>
                <Image x:Name="LoadedImage" Margin="10" Source="{Binding ImagePath}"/>
                <Canvas  x:Name="BackPanel" Margin="10">
                    <Rectangle x:Name="selectionRectangle" Stroke="LightBlue" Fill="#220000FF" Visibility="Collapsed"/>
                </Canvas>
            </Grid>

现在我的困境是如何迁移我后面的代码中使用的实际代码,如下所示:

     private void LoadedImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (isDragging == false)
        {
            anchorPoint.X = e.GetPosition(BackPanel).X;
            anchorPoint.Y = e.GetPosition(BackPanel).Y;
            Canvas.SetZIndex(selectionRectangle, BackPanel.Children.Count);
            isDragging = true;
            BackPanel.Cursor = Cursors.Cross;
        }

    }
    private void LoadedImage_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDragging)
        {
            double x = e.GetPosition(BackPanel).X;
            double y = e.GetPosition(BackPanel).Y;
            selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
            selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
            selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
            selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);

            if (selectionRectangle.Visibility != Visibility.Visible)
                selectionRectangle.Visibility = Visibility.Visible;
        }
    }

    private void LoadedImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (isDragging)
        {
            isDragging = false;
            if (selectionRectangle.Width > 0)
            {
                Crop.IsEnabled = true;
                Cut.IsEnabled = true;
                BackPanel.Cursor = Cursors.Arrow;
            }
        }
    }

如您所见,我需要能够访问x和y坐标以及矩形的宽度和高度(称为选择矩形)。我想在我的viewmodel中创建画布和矩形,但这将违背mvvm结构。我读过我可以使用附加属性但不熟悉它。有关MVVM模式的最佳处理方法是什么?目前我正在阅读Adan Nathan WPF出版的一本书,这对于像我这样的初学者来说是一本很好的书,但我似乎无法找到与我的问题有关的任何内容。谢谢你的帮助

我的鼠标事件有一个视图模型代码:

        #region MouseLeftButtonDown
    private bool isDragging = false;
    private Point anchorPoint = new Point();
    private ICommand _mouseLeftButtonDownCommand;
    public ICommand MouseLeftButtonDownCommand
    {
        get
        {
            if (_mouseLeftButtonDownCommand == null)
            {
                _mouseLeftButtonDownCommand = new RelayCommand(param => MouseLeftButtonDown());
            }
            return _mouseLeftButtonDownCommand;
        }

    }
    public void MouseLeftButtonDown()
    {
        if (isDragging == false)
        {
            MessageBox.Show("THis is Mouse Down");
            //anchorPoint.X = e.GetPosition(BackPanel).X;
            //anchorPoint.Y = e.GetPosition(BackPanel).Y;
            isDragging = true;
        }
    }
    #endregion

    #region MouseLeftButtonUp
    private ICommand _mouseLeftButtonUpCommand;
    public ICommand MouseLeftButtonUpCommand
    {
        get
        {
            if (_mouseLeftButtonUpCommand == null)
            {
                _mouseLeftButtonUpCommand = new RelayCommand(param => MouseLeftButtonUp((MouseButtonEventArgs)param));
            }
            return _mouseLeftButtonUpCommand;
        }

    }

    public void MouseLeftButtonUp(MouseButtonEventArgs e)
    {

        if (isDragging)
        {
            MessageBox.Show(e.Source.ToString());
            isDragging = false;
            //if (selectionRectangle.Width > 0)
            //{
            //    Crop.IsEnabled = true;
            //    Cut.IsEnabled = true;
            //    BackPanel.Cursor = Cursors.Arrow;
            //}
        }
    }
    #endregion

    #region MouseMove
    private ICommand _mouseMoveCommand;
    public ICommand MouseMoveCommand
    {
        get
        {
            if (_mouseMoveCommand == null)
            {
                _mouseMoveCommand = new RelayCommand(param => MouseMove());
            }
            return _mouseMoveCommand;
        }

    }
    public void MouseMove()
    {
        if (isDragging)
        {
            //MessageBox.Show("THis is Mouse Move");
            //double x = e.GetPosition(BackPanel).X;
            //double y = e.GetPosition(BackPanel).Y;
            //selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
            //selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
            //selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
            //selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);

            //if (selectionRectangle.Visibility != Visibility.Visible)
            //    selectionRectangle.Visibility = Visibility.Visible;
        }
    }
    #endregion

我刚刚评论了实际的代码并将其替换为消息框,以测试我的触发器是否正常工作。这三个函数一旦我弄清楚如何使其工作将在裁剪的图像顶部绘制裁剪矩形。我确实有一个裁剪按钮,一旦矩形完成就会启用,这个按钮将被绑定到另一个可能是实际裁剪功能的功能。

2 个答案:

答案 0 :(得分:2)

这比你想象的更简单。

您正在做的是UserControl用户定义的行为。因此,不是将XAML放入您的Page / View,而是实现自己的Control,它源自UserControl并实现您的代码隐藏代码。

由于您正在制作自定义控件,因此您无需关注MVVM。实际上,不鼓励用户控件的MVVM模式。在您的自定义控件中,您可以定义一个依赖属性,该属性包含一个类型为“SelectionRect”的Object(您不应该使用Rect,因为它是一个结构,并且它不能很好地与数据绑定一起使用,因为它创建了一个新的副本每次改变)。

public class CropControl : UserControl 
{
    public Rect Selection
    {
        get { return (Rect)GetValue(SelectionProperty); }
        set { SetValue(SelectionProperty, value); }
    }

    public static readonly DependencyProperty SelectionProperty =
        DependencyProperty.Register("Selection", typeof(Rect), typeof(CropControl), new PropertyMetadata(default(Rect)));

    // this is used, to react on changes from ViewModel. If you assign a  
    // new Rect in your ViewModel you will have to redraw your Rect here
    private static void OnSelectionChanged(System.Windows.DependencyObject d, System.Windows.DependencyPropertyChangedEventArgs e)
    {
        Rect newRect = (Rect)e.NewValue;
        Rectangle selectionRectangle = d as Rectangle;

        if(selectionRectangle!=null)
            return;

        selectionRectangle.SetValue(Canvas.LeftProperty, newRect.X);
        selectionRectangle.SetValue(Canvas.TopProperty, newRect.Y);
        selectionRectangle.Width = newRect.Width;
        selectionRectangle.Height = newRect.Height;
    }

    private void LoadedImage_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        if (isDragging == false)
        {
            anchorPoint.X = e.GetPosition(BackPanel).X;
            anchorPoint.Y = e.GetPosition(BackPanel).Y;
            Canvas.SetZIndex(selectionRectangle, BackPanel.Children.Count);
            isDragging = true;
            BackPanel.Cursor = Cursors.Cross;
        }

    }
    private void LoadedImage_MouseMove(object sender, MouseEventArgs e)
    {
        if (isDragging)
        {
            double x = e.GetPosition(BackPanel).X;
            double y = e.GetPosition(BackPanel).Y;
            selectionRectangle.SetValue(Canvas.LeftProperty, Math.Min(x, anchorPoint.X));
            selectionRectangle.SetValue(Canvas.TopProperty, Math.Min(y, anchorPoint.Y));
            selectionRectangle.Width = Math.Abs(x - anchorPoint.X);
            selectionRectangle.Height = Math.Abs(y - anchorPoint.Y);

            if (selectionRectangle.Visibility != Visibility.Visible)
                selectionRectangle.Visibility = Visibility.Visible;

        }
    }

    private void LoadedImage_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
    {
        if (isDragging)
        {
            isDragging = false;
            if (selectionRectangle.Width > 0)
            {
                Crop.IsEnabled = true;
                Cut.IsEnabled = true;
                BackPanel.Cursor = Cursors.Arrow;
            }

            // Set the Selection to the new rect, when the mouse button has been released
            Selection = new Rect(
                selectionRectangle.GetValue(Canvas.LeftProperty), 
                selectionRectangle.GetValue(Canvas.TopProperty), 
                selectionRectangle.Width,
                selectionRectangle.Height);

        }
    }
}

请注意,唯一的更改是添加Selection = new Rect(...)和依赖项属性。

然后你可以在XAML中绑定它。

<my:CropControl Selection="{Binding Selection,Mode=TwoWay}"/>

<强>更新 您的ViewModel看起来像

public class MyViewModel : ViewModel 
{
    private Rect selection;
    public Rect Selection 
    {
        get 
        {
            return selection;
        }
        set 
        {
            selection = value;

            // Or whatever the name of your framework/implementation the method is called
            OnPropertyChanged("Selection");

            // Cause ICommands to reevaluate their CanExecute methods
            CommandManager.InvalidateRequerySuggested(); 
        }
    }

    private ICommand cropCommand;
    public ICommand CropCommand {
        get 
        {
            if(cropCommand==null)
                cropCommand = new RelayCommand(Crop, () => Selection.Width > 0); // only allow execution when Selection width > 0

            return cropCommand;
        }
    }

    public void Crop() 
    {
        // Get a copy of the selection in case it changes during execution
        Rect cropSelection = Selection; 

        // use it to crop your image
        ... 
    }
}

绘图选择=查看逻辑(所以视图) 使用CropControl =&gt;给出的Rect进行裁剪演示/业务逻辑(所以ViewModel)

这样做可以让您在其他应用程序中重用CropControl。如果将“selectionRect”绘图代码放入ViewModel(这可能会导致难以阅读和维护代码),那么您就无法在其他应用程序中重复使用它,因为您的ViewModel特定于您的应用程序。

希望有所帮助。

答案 1 :(得分:1)

MVVM意味着将View与ViewModel分离。您提供的示例通常是仅查看代码。

您的示例似乎是一种选择工具,我推断您想要获取所选内容,或者至少是裁剪坐标。所以最好是在自定义控件中转换代码,为裁剪坐标公开Rect DependencyProperty,在视图模型中,你应该公开一个保持裁剪矩形坐标的Rect属性,然后绑定它是你的裁剪控制DepencyProperty。

该观点是关于与视觉方面的互动。 ViewModel用于保存和处理视图使用的数据。