MalcomTucker
MalcomTucker

Reputation: 7477

How can I replicate 'float: right' in XAML?

I want to create a ListBoxItem with a layout that includes two areas, one 'float: left' and one 'float: right', with the item overall filling the entire width allocated to the ListBox and the ListBox filling its container (ie. expanding to fill the available space).

How can I achieve this in XAML?

thanks

Upvotes: 11

Views: 10863

Answers (3)

jonramirezp
jonramirezp

Reputation: 31

This is the way I would do it:

    <Style x:Key="ListBoxItemStyle" TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Grid Background="Red">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>

                        <TextBlock Text="{TemplateBinding Content}"/>
                        <TextBlock Text="{TemplateBinding Tag}" Grid.Column="1"/>

                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

</UserControl.Resources>

<Grid x:Name="LayoutRoot" Background="White">

    <ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
        <ListBoxItem Content="Lorem" Tag="Ipsum"/>
        <ListBoxItem Content="Hello" Tag="World"/>
        <ListBoxItem Content="Be" Tag="Happy"/>
    </ListBox>

</Grid>

Upvotes: 1

springy76
springy76

Reputation: 3786

For the "item overall filling the entire width allocated to the ListBox" you need a style like this:

<Style TargetType="ListBoxItem">
    <Setter Property="HorizontalAlignment" Value="Stretch" />
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>

and optionally disable horizontal scrolling for the listbox:

<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled" .. >

for the DataTemplate's root panel you can either use a dockpanel:

<DockPanel>
  <SomeControlLeft DockPanel.Dock="Left" Margin="0 0 5 0" />
  <SomeControlRight DockPanel.Dock="Right" Margin="5 0 0 0" />
  <SomeControlFill />
</DockPanel>

or a grid:

<Grid>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="Auto" />
    <ColumnDefinition Width="5" />
    <ColumnDefinition Width="*" />
    <ColumnDefinition Width="5" />
    <ColumnDefinition Width="Auto" />
  </Grid.ColumnDefinitions>

  <SomeControlLeft Grid.Column="0" />
  <SomeControlRight Grid.Column="4" />
  <SomeControlFill Grid.Column="2" />
</Grid>

Upvotes: 10

qJake
qJake

Reputation: 17139

Use a Grid to position or dock elements to various parts of the form/panel.

Upvotes: 0

Related Questions