1

The xaml dynamic width column will not work

 1 year ago
source link: https://www.codesd.com/item/the-xaml-dynamic-width-column-will-not-work.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The xaml dynamic width column will not work

advertisements

I have been trying to get dynamic column width to work for my simple WP8.1 app. The goal is to have the first column take up half of the listbox, and the other two columns a quarter each. I hoped to do this by assigning a dynamic width, using the * indicator as described here. This let me to the piece of xaml code at the bottom of my post.

In my MainPage I set the DataContext to an ObservableCollection, and all the data shows up in their respective columns, the columns just do not get the desired width (they are all as small as can be). What prevents my dynamic width from working? I have toyed around with HorizontalAlignment and Width of TextBoxes too, but with no success. I tried to look around for answers, and I even used some examples that did work, but that did not bring me closer to understanding why it does not work here.

Thanks in advance.

<Grid>
    <ListBox Name="transactionListBox" ItemsSource="{Binding}">
        <ListBox.ItemTemplate>
              <DataTemplate>
                <Grid Margin="0,0">
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="2*"/>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <TextBlock Grid.Row="0" Grid.Column="0" Text="{Binding Name}"/>
                    <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding Category}"/>
                    <TextBlock Grid.Row="0" Grid.Column="2" Text="{Binding Amount}"/>
                </Grid>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>


The item Grid itself is being sized-to-fit by the ListBox. You can override this behavior by setting the ItemContainerStyle to make the ListBoxItems stretch to fill horizontally:

<ListBox Name="transactionListBox" ItemsSource="{Binding}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="HorizontalAlignment" Value="Stretch" />
            <Setter Property="HorizontalContentAlignment" Value="Stretch" />
        </Style>
    </ListBox.ItemContainerStyle>

    ...
</ListBox>


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK