Noobie3001
Noobie3001

Reputation: 1251

Horizontally stretch a Grid inside a StackPanel with Vertical orientation

I'm trying to make the Grids in this sidebar fill the sidebar which is a stack panel. According to this answer this cannot be done.

My scenario is slightly different as I actually have a ListView with the StackPanel as the ItemsContainer.

I knocked up a quick example to demonstrate:

C#

public partial class MainWindow : Window
{
    public List<string> MyList { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        this.MyList = new List<string> { "foo", "bar", "baz" };
        this.DataContext = this;
    }
}

XAML

    <ListView ItemsSource="{Binding MyList}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <Grid  Background="Orange" 
                       HorizontalAlignment="Stretch">
                    <TextBlock Margin="5"                                    
                               Text="{Binding}"></TextBlock>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Background="Yellow"></StackPanel>
            </ItemsPanelTemplate>
        </ListView.ItemsPanel>
    </ListView>

The result looks like this:

enter image description here

What's the best approach to take here? I want the menu items to bind to a dynamic list and stretch horizontally. I also wish to avoid hard coding a number of RowDefinitions in a Grid instead of using a StackPanel. Is it possible?

Many thanks

Upvotes: 0

Views: 125

Answers (1)

Denis Schaf
Denis Schaf

Reputation: 2739

you need to set the HorizontalContentAlignment to strech its default behaviour is to cramble everything up on the left side:

        <ListView ItemsSource="{Binding MyList}" HorizontalContentAlignment="Stretch">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <Grid  Background="Orange">
                        <TextBlock Text="{Binding}"></TextBlock>
                    </Grid>
                </DataTemplate>
            </ListView.ItemTemplate>
            <ListView.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Background="Yellow"></StackPanel>
                </ItemsPanelTemplate>
            </ListView.ItemsPanel>
        </ListView>

enter image description here

Ps. consider using an ObservableCollection instead of a List<String> in case younplane to update these elements using MVVM

Upvotes: 1

Related Questions