簡體   English   中英

WPF ItemsControl元素-根據窗口大小調整內容大小(錨定)

[英]WPF ItemsControl elements - Resize content based on the window size (Anchoring)

我正在使用wpf,我有一個問題,我想將一個集合綁定到一個元素,該元素根據窗口大小調整其內容的大小。

為了更清楚地說明一個例子:對於靜態行為,我會做類似的事情。

<Grid Margin="10,10,10,10">
    <Grid.RowDefinitions>
        <RowDefinition Height="50*"/>
        <RowDefinition Height="50*"/>
        <RowDefinition Height="50*"/>
        <RowDefinition Height="50*"/>
    </Grid.RowDefinitions>
    <Button Grid.Row="0"></Button>
    <Button Grid.Row="1"></Button>
    <Button Grid.Row="2"></Button>
    <Button Grid.Row="3"></Button>
</Grid>

在這種情況下,所有按鈕都會隨窗口一起增長/縮小。

但是現在我想讓它更具動態性。 我有一個ObservableCollection,其中包含所有要添加的元素(動態量)。 對於第一個實現,我把所有元素都添加到了StackPanel中。 但是StackPanel主體中的控件會調整大小,因此我考慮改為使用網格。

實際解決方案:

<Window.Resources>
    <DataTemplate DataType="{x:Type local:OwnObject}">
        <Button DataContext="{Binding}" Content="{Binding Text}" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
    </DataTemplate>
</Window.Resources>
<Grid>
    <ItemsControl ItemsSource="{Binding SubItems}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel x:Name="stackPanel" Margin="0,0,0,0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</Grid>

如何使用ItemsControl為每個元素生成一行並將其添加到該行? 也歡迎其他解決該問題的解決方案。

您可以使用UniformGrid作為ItemsPanelTemplate因為它是一個網格,在網格中的所有單元格的大小相同。 因此代碼看起來像這樣。

<ItemsControl Name="icTest" VerticalContentAlignment="Stretch">
    <ItemsControl.ItemTemplate>
        <DataTemplate DataType="{x:Type local:OwnObject}">
            <DockPanel Margin="0">
                <Button Content="{Binding Text}" Margin="0,0,0,0"
                        HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            </DockPanel>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="1" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

在后面的代碼中看起來像那樣。

    public class OwnObject : INotifyPropertyChanged
    {
        private string _text;

        public string Text
        {
            get { return _text; }
            set { _text = value; NotifyPropertyChanged( "Text" ); }
        }

...

    }

...

    ObservableCollection<OwnObject> objects = new ObservableCollection<OwnObject>();
    objects.Add( new OwnObject() { Text = "first" } );
    objects.Add( new OwnObject() { Text = "second" } );
    objects.Add( new OwnObject() { Text = "third" } );
    icTest.ItemsSource = objects;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM