Reputation: 103
I am making a kind of navigation bar using a horizontal ListBox
(There is probably a better way) reason being I needed to be able to select only 1 thing at a time, and have it stay selected, then be able to deselect it. So to make that work I'm using a ToggleButton
.
Problem is, I 'Stretch' the content to fit in the box so that I can click anywhere in the selection area to deselect using the togglebutton.
My problem is that my buttons are now top aligned because of the stretch, is it possible to vertical center them whilst using the stretch? Whenever I try and center them at the same time it puts me back to square one where the button itself gets shrunk to the center again.
<ListBox Grid.Row="0" Grid.Column="0" ItemsSource="{Binding PageViewModels}" SelectedItem="{Binding CurrentPageViewModel}" Style="{StaticResource MenuStyle}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="Padding" Value="0"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ListBoxItem}">
<Border Background="{TemplateBinding Background}">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="#FCCC"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="#FAAA"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<ToggleButton VerticalAlignment="Stretch"
Content="{Binding Name}"
IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"
Style="{StaticResource BlankButtonStyle}"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
This is probably a really stupid question but it's really bugging me and I'm a bit stuck.
Upvotes: 0
Views: 4003
Reputation: 103
So I was able to solve this by simply adding a TextBlock to the ListItem template.
I can stretch the now blank ToggleButton to the full size of the ListItem and then center/do whatever with the TextBlock.
It's not an ideal implementation but it's the best one I could come up with for now.
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" />
<ToggleButton VerticalAlignment="Stretch"
Content=""
IsChecked="{Binding IsSelected, Mode=TwoWay, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListBoxItem}}}"
Style="{StaticResource BlankButtonStyle}"
/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
Upvotes: 1
Reputation: 1456
You can use VerticalContentAlignment property.
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="VerticalContentAlignment" Value="Center"/>
...
Upvotes: 1