I have a Listbox with this format
<ListBox x:Name="lbAlbumSelect"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Click="lbAlbumSelect_OnSelectionChanged">
<Button.Content>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<Image Grid.Column="0"
Source="{Binding album_img_src}"
HorizontalAlignment="Left"/>
<TextBlock Grid.Column="1"
TextWrapping="Wrap"
TextAlignment="Right"
HorizontalAlignment="Right"
Margin="2,0,0,0"
Text="{Binding album_name}" />
</Grid>
</Button.Content>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
And It shows data like this
But I want to show data like this
Without HorizontalContentAlignment
set to Stretch
, the ListBoxItem
s wouldn't occupy all the Width of the Parent Control, so I can't remove it. But why Horizontal Alignment=Left
in Image
doesn't work? Is it overridden or something?
You don't need a Button in the ItemTemplate to trigger a SelectionChanged event. Attach a handler for the ListBox's SelectedChanged
event instead:
<ListBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectionChanged="lbAlbumSelect_SelectionChanged">
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="2*"/>
</Grid.ColumnDefinitions>
<Image Source="{Binding album_img_src}"/>
<TextBlock Grid.Column="1" TextAlignment="Center"
Text="{Binding album_name}"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The event handler method gets a SelectionChangedEventArgs
parameter, which can be used to determine in which way the selection has changed:
private void lbAlbumSelect_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
Please note also that there are widely accepted naming convention in the .NET world, where you would use CamelCase for property names. So your view model properties should be AlbumName
and AlbumImgSrc
(or better AlbumImageSource
).