C# WPF MVVM如何从ViewModel中的视图访问矩形集合?
我在ViewModel中有一个带有RaisePropertyChanged的按钮,它将形状中的矩形添加到界面和ObservableCollection中 在视图中,我可以通过单击选定的矩形来移动或调整其大小。它必须在视图中,因为使用Canvas,例如,类似于Window_-Loaded方法C# WPF MVVM如何从ViewModel中的视图访问矩形集合?,c#,wpf,mvvm,C#,Wpf,Mvvm,我在ViewModel中有一个带有RaisePropertyChanged的按钮,它将形状中的矩形添加到界面和ObservableCollection中 在视图中,我可以通过单击选定的矩形来移动或调整其大小。它必须在视图中,因为使用Canvas,例如,类似于Window_-Loaded方法 private void Window_Loaded(object sender, RoutedEventArgs e) { Rectangles = new List
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();
}
不幸的是,列表矩形只包含UI中的“静态”元素,而不是我通过单击按钮添加的元素。我想做的是用我在ViewModel中添加的矩形填充这个列表。欢迎提出任何建议
我试图做的是计算添加的矩形,然后使用相同数量的新对象填充矩形,但它看起来应该具有界面上对象的属性,以允许交互。这假设您的虚拟机中有一个名为
ShapeVM
的observeCollection
对象,该对象具有适当的属性(例如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>
请注意,如果您将拥有数千个形状,这种绑定是不合适的,因为性能将是一个问题
<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>