Reputation: 1
How can i dynamic align the listview items in a listview.
-- NOT IN XAML --
lv.View = GridView
GridView.Columns.Add(New GridViewColumn With {.Header = "CrewId", .DisplayMemberBinding = New Binding("CrewId")})
GridView.Columns.Add(New GridViewColumn With {.Header = "FirstName", .DisplayMemberBinding = New Binding("FirstName")})
GridView.Columns.Add(New GridViewColumn With {.Header = "LastName", .DisplayMemberBinding = New Binding("LastName")})
GridView.Columns.Add(New GridViewColumn With {.Header = "Country", .DisplayMemberBinding = New Binding("Country")})
GridView.Columns.Add(New GridViewColumn With {.Header = "Rank", .DisplayMemberBinding = New Binding("Rank")})
Try
lv.ItemsSource = dsCrew.Tables(0).DefaultView
Catch ex As Exception
MsgBox(ex.Message)
End Try
Upvotes: 0
Views: 1736
Reputation: 69985
You can simply use the HorizontalContentAlignment
property to align all of the ListViewItem
s:
lv.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Right;
UPDATE >>>
Ahh, that's why this solution didn't work... you have more than one column. Of course I couldn't tell that before you showed your code. Ok, I found a way to align all of the columns to the right... I understand that this is not exactly what you're after, but I'll add this here until I find a better solution:
Style style = new Style(typeof(ListViewItem));
style.Setters.Add(new Setter(ListViewItem.HorizontalContentAlignmentProperty,
HorizontalAlignment.Right));
YourListView.ItemContainerStyle = style;
You may be able to work out the rest in the meantime.
UPDATE 2 >>>
OK, so I've had a good search online and this is the closest that I've come to an answer for you... there is an article called How to center and right align text inside a GridViewColumn in a WPF ListView Control on Tracy Sells' website which shows how to do this in XAML... yes, I know you wanted it in code, but you'll have to do some of the work here:
<ListView
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
</ListView.ItemContainerStyle>
<ListView.View>
<GridView>
<GridViewColumn>
<TextBlock Text="MyText" TextAlignment="Center" />
</GridViewColumn>
</GridView>
<ListView.View>
</ListView>
We can adapt my second bit of code to implement the ItemContainerStyle
:
Style style = new Style(typeof(ListViewItem));
style.Setters.Add(new Setter(ListViewItem.HorizontalContentAlignmentProperty,
HorizontalAlignment.Stretch));
YourListView.ItemContainerStyle = style;
That's as far as I can go unfortunately, as I've never actually used a ListView
. So now, you just need to find out how to set the TextAlignment
on the content of the relevant GridViewColumn
. I noticed that there is not much help with doing this kind of stuff in code and that is simply because this is not the usual way of doing it. Either way, good luck with finding out how to accomplish the last part of the puzzle.
Upvotes: 1