.net - 拉伸(stretch) WrapPanel 项目

标签 .net wpf xaml .net-4.5 wrappanel

我在其中有 WrapPanel 和非常相似的项目。也许 WrapPanel 是一个错误的容器,只是描述了我所拥有的。

我希望所有项目都具有相同的宽度;最小宽度为 120。另外,我希望项目可以拉伸(stretch),这就是重点。

如果 WrapPanel 宽度为 150(小于 2*minimum),将有一列,项目的宽度将为 150。

如果 WrapPanel 宽度为 350(小于 3*最小值),将有两列,项目的宽度将为 175 (350/2)。

如果 WrapPanel 宽度为 370(小于 4*最小值),则将有三列,项目的宽度将为 123 (370/3)。也可以是123的两项,124的一项,无所谓。

问题是我怎样才能得到这种行为?

最佳答案

C#代码:

public MainWindow()
{
    DataContext = this;
    SomeList.Add(new SomeType());
    SomeList.Add(new SomeType());
    SomeList.Add(new SomeType());
    SomeList.Add(new SomeType());
    SomeList.Add(new SomeType());
    InitializeComponent();
}
//SomeList Observable Collection
private ObservableCollection<SomeType> _someList =
    new ObservableCollection<SomeType>();
public ObservableCollection<SomeType> SomeList { get { return _someList; } }
private void UniformGrid_SizeChanged(object sender, SizeChangedEventArgs e)
{
    var grid = sender as UniformGrid;
    if (grid.ActualWidth > 370) grid.Columns = 3;
    else if (grid.ActualWidth > 150) grid.Columns = 2;
    else grid.Columns = 1;
}
public class SomeType : DependencyObject
{
    //Title Dependency Property
    public string Title
    {
        get { return (string)GetValue(TitleProperty); }
        set { SetValue(TitleProperty, value); }
    }
    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(SomeType),
        new UIPropertyMetadata("unset yet"));
}

XAML 代码:

<Window.Resources>
    <DataTemplate x:Key="SomeTemplate" DataType="{x:Type local:SomeType}">
        <Border BorderBrush="Black" BorderThickness="2" CornerRadius="4">
            <TextBlock Text="{Binding Title}"/>
        </Border>
    </DataTemplate>
</Window.Resources>
<ItemsControl
    ItemsSource="{Binding SomeList}"
    ItemTemplate="{StaticResource SomeTemplate}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid SizeChanged="UniformGrid_SizeChanged"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

关于.net - 拉伸(stretch) WrapPanel 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13127905/

相关文章:

.net - 在 Windows 8 应用程序中没有 FileTypeFilter 的 FileOpenPicker

WPF 后台渲染控件

WPF:使用 WPF UserControl 的优点/缺点是什么?

c# - 尝试捕捉骰子滚动问题和复选框问题

c# - 多个 Linq 函数作为参数

c# - 选择部分显示的 WPF 复选框

c++ - 如何从 c++ winrt UWP 应用程序中的代码将文本添加到 RichTextBlock,

c# - 如何在内容控件上显示数据模板?

.net - 如何使用 Moq 模拟 ISerializable 类?

c# - Passwordbox Validation.ErrorTemplate 未显示