c# - WPF MVVM 如何从 ViewModel 中的视图访问矩形集合?
问题描述
我在 ViewModel 中有一个带有 RaisePropertyChanged 的按钮,它将形状中的矩形添加到界面和 ObservableCollection。
在视图中,我可以通过单击它们来移动或调整选定矩形的大小。它必须在 View 中,因为使用 Canvas,例如在 Window_Loaded 方法中。
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Rectangles = new List<Rectangle>();
foreach (UIElement child in canvas1.Children)
{
if (child is Rectangle)
Rectangles.Add(child as Rectangle);
}
// Reverse the list so the Rectangles on top come first.
Rectangles.Reverse();
}
或 canvas1_MouseDown
private void canvas1_MouseDown(object sender, MouseButtonEventArgs e)
{
FindHit(Mouse.GetPosition(canvas1));
SetMouseCursor();
if (MouseHitType == HitType.None) return;
LastPoint = Mouse.GetPosition(canvas1);
DragInProgress = true;
}
不幸的是,List Rectangles 仅包含 UI 中的“静态”元素,而不是我通过单击按钮添加的元素。我要做的是用我在 ViewModel 中添加的矩形填充这个列表。任何建议都热烈欢迎。
我试图做的是计算添加的矩形并使用相同数量的新对象填充矩形,但看起来它应该在界面上具有对象的属性以允许交互。
解决方案
这假设您在您的虚拟机中ObservableCollection
调用Shapes
了某种ShapeVM
具有适当属性的对象(例如RectVM
,具有宽度和高度等)
当ItemsControl
基础集合更改时,将自动将它们添加到视图中。
<ItemsControl ItemsSource="{Binding Shapes}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.Resources>
<DataTemplate DataType="{x:Type vm:RectVM}">
<Rectangle Canvas.Left="{Binding X}"
Canvas.Top="{Binding Y}"
Width="{Binding Width}"
Height="{Binding Height}" />
</DataTemplate>
</ItemsControl.Resources>
</ItemsControl>
请注意,如果您将拥有数千个形状,则这种绑定是不合适的,因为性能将是一个问题。
推荐阅读
- flutter - 如何在颤动中更改快餐栏的不透明度?
- python - 将随机变量传递给 agg 函数 python
- c - 如何在 execl() 函数中更改时区(TZ=UTC)输出。
- php - 考试 Qn:将 do while 循环转换为 for 循环 (PHP)
- ssis - SSIS ADO.Net 连接器火灾触发器
- javascript - 在 Postman 的 URL 中传递全局变量
- angular - 如何将 Mat-Card 组件中的内容居中 - Angular 6
- php - 在 PHP 7.2 上使用 Symfony 会话的 `migrate` 方法会引发错误
- proguard - Proguard:使用具有特定注释的 main() 混淆类
- sql - 如何从列列表中进行选择?SQL 服务器