Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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

like image 924
MalcomTucker Avatar asked Sep 14 '11 18:09

MalcomTucker


2 Answers

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>
like image 54
springy76 Avatar answered Nov 19 '22 17:11

springy76


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>
like image 34
jonramirezp Avatar answered Nov 19 '22 16:11

jonramirezp