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
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With