【问题标题】:How can I position ViewModels in an ItemsControl如何在 ItemsControl 中定位 ViewModel
【发布时间】:2011-03-10 15:10:00
【问题描述】:

我的主窗口 ViewModel 有一个 ViewModel 的 ObservableCollection,称为 ViewModels。

主窗口 XAML 有一个 ItemsControl,其中 ItemsSource 绑定到 ViewModel。

当我有

<ItemsControl ItemsSource="{Binding ViewModels}" />

与集合中的每个 ViewModel 关联的 Views 呈现在另一个之下。视图是用户控件,显示数据网格。

如何以可自定义的方式定位它们,例如 VM1 位于左侧,VM2 和 VM3 一个在另一个之上堆叠在 VM1 的右侧。

每个 VieModel 都有 PosX、PosY、Width 和 Height 属性,我一直在尝试各种模板方法,但到目前为止都没有成功。

我已经找到了如何使用 Observable 图像集合来实现这一点的示例,但我正在苦苦挣扎的一件事是我的集合是 ViewModels。

【问题讨论】:

  • 我需要像你所做的那样使用 observablecollections 在 itemsControls 中显示与不同视图模型相关联的不同视图。我是 WPF 的新手。你能和我分享你的代码吗!
  • @Manish Dubey,请参阅下面接受的答案中的代码

标签: wpf itemscontrol templating wpf-positioning


【解决方案1】:

将您的 ItemsControl.ItemsPanel 制作成 Canvas,并在 ItemTemplate 中设置您的 Top/Left/Height/Width。

<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>

【讨论】:

  • 谢谢 Rachel,但我也不需要 DataTemplate。使用您的解决方案运行我得到一个空白画布,而正如我上面所说,省略了所有 ItemsControl 内部的东西,我让我的 ViewModels 堆叠在一起。
  • @GilShalit 是的,您需要一个 DataTemplate。我以为你已经涵盖了,对不起。我加进去
  • 快到了,在您的帮助下...现在我正在让第一个视图模型显示正常,但我在 left=VM1.width 设置的第二个视图模型没有显示。有任何想法吗? ClipToBounds 在这种情况下做了什么?
  • @GilShalit VM2.Left、Top、Height 和 Width 设置是否正确?我会先验证这些值是否正确。其次,检查并确保 Canvas 足够大以适合其内容。我通常通过设置 Canvas 的背景颜色来做到这一点,这样我就可以看到它正在使用的空间。 ClipToBounds 就在那里,因为我从我拥有的一些代码中复制/粘贴了该行并且没有同时删除它。如果大小超过画布中的可用空间,它会剪切对象。
  • 显然我检查并仔细检查了...但是现在,在您的敦促下,我再次检查了,对于 VM2,值被设置在一个未被调用的函数中...谢谢你的所有帮助。
猜你喜欢
  • 2016-10-11
  • 1970-01-01
  • 2014-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多