如何将ViewModels放置在ItemsControl中 [英] How can I position ViewModels in an ItemsControl
问题描述
我的主窗口ViewModel有一个名为ViewModels的ViewModel的ObservableCollection.
My mainwindow ViewModel has an ObservableCollection of ViewModels, called ViewModels.
Mainwindow XAML具有一个ItemsControl,并将ItemsSource绑定到ViewModels.
The Mainwindow XAML has an ItemsControl with ItemsSource bound to ViewModels.
当我有
<ItemsControl ItemsSource="{Binding ViewModels}" />
与集合中每个ViewModel关联的View呈现在另一个视图之下.视图是UserControls,显示dataGrids.
The Views associated with each ViewModel in the collection are rendered one below the other. The Views are UserControls, displaying dataGrids.
如何以可自定义的方式放置它们,例如,VM1位于左侧,而VM2和VM3则一个接一个地堆叠在VM1的右侧.
How can I position them in a customizable way, for example such that VM1 is on the left, and VM2 and VM3 are stacked one on top of the other to the right of VM1.
每个VieModel都具有PosX,PosY,Width和Height属性,我一直在尝试各种模板化方法,但到目前为止没有成功.
Each VieModel has PosX, PosY, Width and Height properties, and I've been trying various templating methods but no success so far.
我在Observable图像集合中找到了如何做到这一点的示例,但我苦苦挣扎的一件事是我的集合是ViewModels.
I have found examples of how to this with Observable collections of images, but one thing I'm struggling is that my collection is of ViewModels.
推荐答案
将ItemsControl.ItemsPanel制成画布,并在ItemTemplate中设置顶部/左侧/高度/宽度.
Make your ItemsControl.ItemsPanel into a Canvas, and set your Top/Left/Height/Width in the ItemTemplate.
<ItemsControl ItemsSource="{Binding ViewModels}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<!-- Height, Width, and Background are required to render size correctly -->
<Canvas Height="600" Width="800" Background="White" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="{x:Type FrameworkElement}">
<Setter Property="Canvas.Top" Value="{Binding Top}" />
<Setter Property="Canvas.Left" Value="{Binding Left}" />
<Setter Property="Height" Value="{Binding Height}" />
<Setter Property="Width" Value="{Binding Width}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl>
<ContentPresenter ClipToBounds="True" Content="{TemplateBinding Content}"/>
</ContentControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
这篇关于如何将ViewModels放置在ItemsControl中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!