【发布时间】:2021-05-24 14:56:21
【问题描述】:
我是 WPF 新手,我想使用 MVVM 模式创建一个程序(不使用 MvvmLight 等外部库)。该应用程序允许用户使用鼠标在画布内绘制矩形(以及未来的其他形状)(类似于 Windows Paint,只是为了清楚起见)。用户也可以使用鼠标交互来移动/调整创建的矩形。
此时我实现了一个基本版本,用户可以通过单击按钮添加一个矩形(具有随机大小/位置)。这是实现此行为的 MainWindow 视图的代码:
...
Title="{Binding Path=Titolo}"
Height="450" Width="800"
d:DataContext="{d:DesignInstance vm:MainWindowViewModel}">
<StackPanel>
<StackPanel Orientation="Horizontal">
<Button Content="Add Rectangle" Command="{Binding AddShapeCommand}" />
</StackPanel>
<Canvas>
<ItemsControl ItemsSource="{Binding AllShapeCollection}">
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type vm:MyRectViewModel}">
<uc:MyRectView/>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Left" Value="{Binding xLT}" />
<Setter Property="Canvas.Top" Value="{Binding yLT}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
</Canvas>
</StackPanel>
Usercontrol MyRectView 定义如下:
<UserControl x:Class="MVVM_TestRect.Views.MyRectView"
...
xmlns:vm="clr-namespace:MVVM_TestRect.ViewModels"
xmlns:local="clr-namespace:MVVM_TestRect.Views"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance vm:MyRectViewModel}"
Width="auto" Height="auto">
<Grid>
<Rectangle Width="{Binding Path=Width, Mode=TwoWay}"
Height="{Binding Path=Height, Mode=TwoWay}"
Fill="Green"/>
</Grid>
</UserControl>
程序按方面工作,绑定似乎没问题。
现在,如前所述,我将使用鼠标和移动/调整形状的能力来实现绘图。 我找到了很多例子,但没有人能解决我的疑惑:
- MVVM 模式不允许将事件处理程序(用于鼠标交互)放在视图代码隐藏中,那么我应该在哪里编写事件处理程序?
- MouseAction (msdn description here) 似乎不合适,因为缺少可能的交互(即按钮向上、移动);我应该考虑哪些替代方案?
- 鼠标交互应该由绘制形状的画布处理还是由形状本身处理?
- MVVM 是否适合用于此类应用程序?
【问题讨论】: