【问题标题】:Stretch WrapPanel items拉伸 WrapPanel 项目
【发布时间】:2012-10-19 03:18:43
【问题描述】:

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

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

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

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

如果 WrapPanel 宽度为 370(小于 4*最小值),则将有三列,项目的宽度将为 123 (370/3)。也可以是123的2个,124的1个,没关系。

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

【问题讨论】:

  • 是否自动设置列号?我没有找到这个功能。
  • 是的,如果您将其行设置为“1”,那么您甚至不必为每个元素设置行或列。
  • 无法正常工作。你能举一个小例子作为答案吗?
  • 您是否尝试设置 MinWidth=120 Width=* Horizo​​ntal/ContentAlignment=Stretch per object?
  • 是的,我做到了。我也试过设置 MaxWidth。

标签: .net wpf xaml .net-4.5 wrappanel


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2018-02-25
    • 1970-01-01
    • 2016-02-26
    • 2021-05-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多