【问题标题】:How to arrange controls horizontally with even spacing in WPF如何在WPF中以均匀间距水平排列控件
【发布时间】:2015-07-01 20:26:08
【问题描述】:

我正在寻找一种灵活的方法来在网格内以均匀的间距排列矩形控件。控件是动态添加/删除的。最终我希望让用户选择以下布局之一:

我正在考虑使用 UniformGrid 并让其余的由网格的属性处理:

<UniformGrid>
    <Button Content="Button 1"/>
    <Button Content="Button 2"/>
    <Button Content="Button 3"/>
    <Button Content="Button 4"/>
    <Button Content="Button 5"/>
</UniformGrid>

但是,我担心的是我未来能否像选项 3 那样自定义布局(见上图)。考虑到我在设计中遵循 MVVM,我正在寻找有关如何使其尽可能灵活的建议。

【问题讨论】:

  • 如果您知道按钮的尺寸,以及要放入它们的任何容器的尺寸,WrapPanel 和一些边距设置可能会完成这项工作。
  • 我个人会使用ItemsControl 并将ItemsPanelTemplate 设置为UniformGridWrapPanelGrid,具体取决于您的要求。该控件旨在以统一的方式显示对象集合,并且可以轻松地对其进行样式/模板化以以您想要的任何方式显示项目。
  • @Rachel 你提到了 WrapPanel,我更仔细地研究了它,所以现在很惊讶我没有过多关注它。将此添加到答案中,我会标记它,对我有用。
  • @eYe 当然,答案已发布:)

标签: wpf mvvm controls docking


【解决方案1】:

使用 UniformGrid 并绑定列和行的计数。将其用作项目控件的面板,您可以获得 MVVM 分离。

<ItemsControl ItemsSource={Binding X}>
    <ItemsControl.ItemsPanel>
       <ItemsPanelTemplate>
          <UniformGrid Rows={Binding...} />
     </ItemsPanelTemplate>    
   </ItemsControl.ItemsPanel>
</ItemsControl>

【讨论】:

    【解决方案2】:

    WrapPanel 可用于显示任意数量的项目,如果项目超过允许的宽度,将自动换行。

    <WrapPanel>
        <Button Content="Button 1"/>
        <Button Content="Button 2"/>
        <Button Content="Button 3"/>
        <Button Content="Button 4"/>
        <Button Content="Button 5"/>
    </WrapPanel>
    

    或者,如果您正在寻找可以为控件定义动态布局的更结构化的东西,我建议将ItemsControl 设置为ItemsPanelTemplate 设置为UniformGridWrapPanel 或@ 987654328@ 取决于您的要求。 James Lucas' answer 提供了一个很好的例子。

    【讨论】:

      猜你喜欢
      • 2016-08-06
      • 2014-06-07
      • 1970-01-01
      • 2017-01-31
      • 2015-11-19
      • 1970-01-01
      • 2012-01-14
      • 2013-04-01
      • 2013-07-19
      相关资源
      最近更新 更多