Vertical gridlines in a ListView - wpf

I've got a WPF ListView that I'm using as a GridView. Is there any way I can get vertical gridlines in there?
The ListView has a MinHeight specified, so I'd like the GridLine to go all the way to the bottom of the grid, so it'll fill the empty space.
This seems to be a rather tricky problem. Is is possible to solve?

This is how I do it.
<ListView Grid.IsSharedSizeScope="True"
ItemsSource="{Binding Path=MyList,FallbackValue='12345'}" >
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" SharedSizeGroup="col0"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="1*" SharedSizeGroup="col2"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="10,0"
Text="{Binding Path=Name, FallbackValue='Name goes here'}"/>
<Border Grid.Column="1" Margin="0,-2"
BorderBrush="DarkGray"
BorderThickness="0,0,1,0" />
<TextBlock Grid.Column="2" Margin="10,0"
Text="{Binding Path=DateModified, FallbackValue='Date goes here'}"/>
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
The SharedSizeGroup and Grid.IsSharedSizeScope properties are key to this way of doing it. The Margin="0,-2" property on the Border makes sure the dividing line looks like a continuous vertical line. If you add vertical margin to the two textblocks, you will need to increase the negative vertical margin of the border.
This will take care of lining things up into two uniformly sized columns with a vertical line between them, but it won't extend into areas where there is no data. A ListView might not be the best option if you want that functionality.
Adding some data to the MyList property in the ViewModel gives this as a result:
Of course, the MyList property needs to be a list or collection of a class that has Name and DateModified as properties.

Related

How to align buttons horizontally and spread equally with xaml windows phone

I have an ObservableCollection which contains ViewModel which in turns defines my buttons definitions.
I've been at it for hours, reading articles after articles but to no avail. I've tried using a Listbox and this is the closest I've got to. My buttons are getting build horizontally but assuming I'm displaying 3 buttons, I want one displayed on the left, one displayed in the middle and one displayed on the right.
<ListBox Grid.Row="2" ItemsSource="{Binding Links}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<StackPanel Background="Beige" Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Grid.Column="{Binding Column}"
Grid.Row="0"
Width="90"
Height="90">
<ContentControl>
<StackPanel Orientation="Vertical">
<Image Source="{Binding Image}" Width="36" Height="36"
Margin="5" Stretch="UniformToFill"
HorizontalAlignment="Center"/>
<TextBlock Text="{Binding Description}"
Foreground="#0F558E"
FontSize="18"
HorizontalAlignment="Center"/>
</StackPanel>
</ContentControl>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>
As you can see, I set the column dynamically using a property from my ViewModel but I no longer have a grid as I couldn't get it to work, but ideally I'd like to use a grid so that I can specify in which Column to set the button.
When I use a StackPanel, it works but the buttons are right next to each other rather than being split evenly through the entire width of the screen.
I've done something similar to the above using ItemsControl and using a grid, and I can see each button getting added but they overlap each other in row 0, col 0. If I bind the row to the Column property for testing purposes, it build it correctly but my buttons are displayed on different rows which is not what I want. I want each button to be aligned horizontally.
How can I achieve this? I know I could just hard code 3 buttons and just change their icons and text and handle the relevant code by passing the relevant button as binded parameter, but ideally I'd like to build the buttons dynamically in a grid and position them using the column.
Note that the number of column would be fixed i.e. 3, as I'll never have more than this.
Thanks.
but ideally I'd like to use a grid so that I can specify in which
Column to set the button.
In any Xaml variant, why not just use that Grid, such as shown below, where the Grid is set to consumes all the horizontal space.
Then with the grid's center column to be star sized and to have the rest of the remaining space be consumed after button 1 and button 3, which auto size into their own spaces:
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button Grid.Column="0"/>
<Button Grid.Column="1" HorizontalAlignment="Center"/>
<Button Grid.Column="2"/>
</Grid>
If that fails, set button one's HorizontalAlignment to be Left and button three's as Right.
As an aside with the list box, it may not be stretching to the whole horizontal size of the screen. Check out my answer to a WP8 sizing issue:
ListBoxItem HorizontalContentAlignment.
I eventually found the answer to my problem in an article I found on the web.
You can check it out here: Using Grids with ItemsControl in XAML
In short, you need to subclass the itemsControl and you need overwrite the GetContainerForItemOverride method which will take care of copying the "data" of the ItemTemplate to the ContentPresenter. In this instance, the row and column, but for my requirement, it is just the Column, since my row will always be 0.
Here is core part of the code if you don't want to check the full article which resolve the problem of setting controls horizontally in a grid using ItemsControl but note the article takes care of creating rows & columns dynamically as well, which I'm not interested in for my project.
public class GridAwareItemsControl : ItemsControl
{
protected override DependencyObject GetContainerForItemOverride()
{
ContentPresenter container = (ContentPresenter)base.GetContainerForItemOverride();
if (ItemTemplate == null)
{
return container;
}
FrameworkElement content = (FrameworkElement)ItemTemplate.LoadContent();
BindingExpression rowBinding = content.GetBindingExpression(Grid.RowProperty);
BindingExpression columnBinding = content.GetBindingExpression(Grid.ColumnProperty);
if (rowBinding != null)
{
container.SetBinding(Grid.RowProperty, rowBinding.ParentBinding);
}
if (columnBinding != null)
{
container.SetBinding(Grid.ColumnProperty, columnBinding.ParentBinding);
}
return container;
}
}
The final xaml looks like this:
<controls:GridAwareItemsControl ItemsSource="{Binding Links}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid Background="Pink">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button
Grid.Column="{Binding Column}"
Grid.Row="0"
Width="120" Height="120">
<ContentControl>
<StackPanel Orientation="Vertical">
<Image Source="{Binding Image}" Width="36" Height="36" Margin="5"
Stretch="UniformToFill" HorizontalAlignment="Center"/>
<TextBlock Text="{Binding Description}" Foreground="#0F558E"
FontSize="18" HorizontalAlignment="Center"/>
</StackPanel>
</ContentControl>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</controls:GridAwareItemsControl>
Once I used the new control, my buttons were correctly placed inside the grid, and therefore were evenly spaced out as the grid took care of that wit the ColumnDefinitions.
If anyone knows how to achieve the same without having to create a new control and overriding the method (in other words, pure XAML), please post it as I'd be very interested to see how this can be done.
Thanks and thank you to Robert Garfoot for sharing this great code!
PS: Note that I've simplified my xaml in order to create a test sample without any style on the buttons, so these are rather large if you try based on this sample.
UPDATE:
Small typo correction but my grid column definition was defined as
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
but as #OmegaMan suggested, to be evenly spread, it should have been defined as
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
I was able to accomplish this with a stackpanel inside of a grid, avoiding columns altogether. If you set the stackepanel's HorizontalAlignment to "center", it will center itself inside the grid and grow as buttons are added, still staying centered inside of the grid. Then it's just a matter of margins to have the buttons equally spaced:
<Grid>
<StackPanel
VerticalAlignment="Stretch"
HorizontalAlignment="Center"
Orientation="Horizontal"
>
<Button HorizontalAlignment="Center" Content="Add" Width="104" Height="32" Margin="24,0"/>
<Button HorizontalAlignment="Center" Content="Edit" Width="104" Height="32" Margin="24,0"/>
<Button HorizontalAlignment="Center" Content="Remove" Width="104" Height="32" Margin="24,0"/>
</StackPanel></Grid>

How to prevent ItemsControl from horizontally stretching to fit children

I have an ItemsControl, nothing fancy:-
<ItemsControl ItemsSource="{Binding ...}"
ItemTemplate="{StaticResource ...}" />
The ItemTemplate contains the following XAML:-
<Border BorderThickness="0,0,0,1"
BorderBrush="LightGray"
Padding="0,2,0,2">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"
SharedSizeGroup="Prompt" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0"
Text="{Binding ...}" />
<NumericUpDown Grid.Column="1"
Width="75"
Text="{Binding ...}" />
</Grid>
</Border>
This produces a UI looking like this:-
However if the text in the TextBlock is very long, it pushes the NumericUpDown off the r.h. edge of the ItemsControl, e.g.:-
I was hoping that once the NumericUpDown had been "pushed up" against the r.h. edge of the ItemsControl, the TextBlock would then start getting truncated. I assume the current behaviour is due to the ItemsControl using a StackPanel as its items presenter. How can I get it to do what I want?
When you are using SharedSizeGroup with Grid.IsSharedSizeScope="True" the column's Star sizing is treated as Auto, more not official informations here.
The IsSharedSizeScope should not be used for arranging the controls described in the question. You should remove all SharedSizeGroup attributes and set the ItemsControl's HorizontalAlignment to Left.
I think that you might want to try setting the Control.HorizontalContentAlignment Property to Stretch on your ItemsControl. According to the linked page, this:
Gets or sets the horizontal alignment of the control's content.
In plain English, this means that it should set the Width of the rendered children, or items, to the same Width as the ItemsControl.
After a lot of running into dead-ends thinking I could resolve this by changing the ItemsPresenter or ItemsPanel, I ended up using a DockPanel within my ItemTemplate, instead of the grid:-
<Border BorderThickness="0,0,0,1"
BorderBrush="LightGray"
Padding="0,2,0,2">
<DockPanel LastChildFill="true">
<NumericUpDown DockPanel.Dock="Right"
Width="75"
Text="{Binding ...}" />
<TextBlock Text="{Binding ...}" />
</DockPanel>
</Border>
I'm not entirely sure why the DockPanel respects the size of the parent ItemsControl, while the Grid was happy to horizontally "overrun" off the edge. This is an aspect of WPF that I still struggle with - which controls' sizes are affected by their parent, and which are affected by their children's sizes!

WPF ListView TextBlock TextWrapping

I am building a ListView that needs to have five columns - the first one needs to have text that can be any length and needs to wrap whenever the window size changes (in addition to changing the row height so the wrapped text is visible) and the other four columns are a static width of 45. I've been searching for hours on this and every solution I come across either requires a static width or doesn't work.
Solutions tried:
Column widths of auto, 1*, 2*, etc. (settings ignored)
DockPanel (settings ignored)
WrapPanel (ignored)
Setting Width to RelativeSource of parent for ActualWidth (ignored)
Any ideas? It seems like a significant number of people have had this same problem, but I would highly prefer to not have to go the static width route for this column. Especially since the content just gets cut off when I do that anyway (even with height="Auto" for the row). The width of the overall window could be as small as 1024, but could also be 1600+ which is why I want dynamic sizing. That way smaller screens will have the content wrap and larger screens will just show the one line since the content fits.
Here is the XAML:
<ListView.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition Width="45" />
<ColumnDefinition Width="45" />
<ColumnDefinition Width="45" />
<ColumnDefinition Width="45" />
</Grid.ColumnDefinitions>
<!-- This is the TextBlock that needs to wrap its content (and
change the height of the row (so the full content is still
visible) to whatever the available space is, but should not
make overall ListView wider than the parent's width. -->
<TextBlock Text="{Binding Content}" Padding="20,6,6,6" />
<!-- These four blocks will have other content eventually, but only need
to be 45 wide -->
<TextBlock Text="X" Grid.Column="1" HorizontalAlignment="Center" />
<TextBlock Text="X" Grid.Column="2" HorizontalAlignment="Center" />
<TextBlock Text="X" Grid.Column="3" HorizontalAlignment="Center" />
<TextBlock Text="X" Grid.Column="4" HorizontalAlignment="Center" />
</Grid>
</DataTemplate>
</ListView.ItemTemplate>
Not so easy...but it can be done.
I wrote a solution for you. In short, use Expression Blend to create a copy of the ListView Template and delete the ScrollViewer surrounding the ItemPresenter.
Here is a more indepth explanation:
How to have the TextBlock in a left column of a Grid in a ListView Template expand or shrink with text wrapping?
<ListView HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListView.ItemTemplate>
...
</ListView.ItemTemplate>
</ListView>
I'd add TextWrapping="Wrap" to the first TextBlock element.

WPF Listbox wont scroll Vertical

Within a Groupbox I have a Listbox, ListboxItems are defined in the XAML as well. The Listbox is defined:
<ListBox Name="lvAvoidCountry" Margin="5,5,5,5"
Background="Transparent"
ScrollViewer.VerticalScrollBarVisibility="Visible"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" >
Items are defined like this:
<ListViewItem >
<CheckBox Name="chkAlbanien" Tag="55">
<StackPanel Orientation="Horizontal">
<Image Source="images/flag_albania.png" Height="30"></Image>
<TextBlock Text="Albanien" Margin="5,0,0,0"></TextBlock>
</StackPanel>
</CheckBox>
</ListViewItem>
If I remove the Scrollviewer Settings I get horizontal scrolling and the Items are well formatted - correct width. If I use the scrollviewer settings the items get cut off so that all items are placed on the listbox. (eg. the flag is shown, the checkbox is shown but the text is just "Alba").
Thanks for any hints!
As the name implies, ScrollViewer.HorizontalScrollBarVisibility="Disabled" disables horizontal scrolling. If you do that, but your ListBoxItems are too long, they'll get cut off. The StackPanel won't grow or shrink to fit into the ListBox, and it won't "wrap" your items to fit into the ListBox if it's too narrow, even if you add TextWrapping to the TextBlock. It's very stubborn. I think your main problem is that StackPanel.
Instead of a StackPanel, try using a Grid with 2 columns defined like so:
<ListViewItem >
<CheckBox Name="chkAlbanien" Tag="55">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Image Grid.Column="0" Source="images/flag_albania.png" Height="30"/>
<TextBlock Grid.Column="1"
TextWrapping="Wrap"
Text="Albanien" Margin="5,0,0,0"/>
</Grid>
</CheckBox>
</ListViewItem>
Auto will "shrinkwrap" the image columns, and * will give the text all remaining space. Then add TextWrapping to your textblock in case it's still too long.
Edited: added more complete code example and changed my answer slightly.
if you want vertical scrolling in a listbox then don't put it in a stackpanel,instead use a grid.

WPF Grid Column MaxWidth not enforced

This problem stems from not being able to get my TextBlock to wrap. Basically as a last-ditch attempt I am setting MaxWidth on my container grid's columns. I was surprised to find that my child label and textbox still do whatever they want (bad children, BAD) and are not limited by my grid column's MaxWidth="200".
What I'm really trying to do is let my TextBlock fill available width and wrap if necessary. So far after trying many variations of HorizontalAlignment="Stretch" on every known parent in the universe, nothing works, except setting an explicit MaxWidth="400" or whatever number on the TextBlock. This is not good because I need the TextBlock to fill available width, not be limited by some fixed number. Thanks!
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition MaxWidth="200" SharedSizeGroup="A" />
<ColumnDefinition MaxWidth="200" SharedSizeGroup="B" />
</Grid.ColumnDefinitions>
<Label VerticalAlignment="Top" Margin="0 5 0 0" Grid.Column="0" Style="{StaticResource LabelStyle}" Width="Auto" Content="{Binding Value.Summary}" />
<TextBlock Grid.Column="1" Margin="5,8,5,8" FontWeight="Normal"
Background="AliceBlue"
Foreground="Black" Text="{Binding Value.Description}"
HorizontalAlignment="Stretch"
TextWrapping="Wrap" Height="Auto" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
I've tried to replicate your problem by pasting everything between your Grid elements in to Kaxaml but everything wraps as you would expect it to. (I inserted regular strings where you were doing bindings and removed the Label style).
It could be that the problem is higher up the tree.
I'd suggest pasting chunks in to Kaxaml or similar to test and see which parent breaks your UI.
I provided an answer to this question, only it was using an ListView instead of an ItemsControl but the issue is likely the same. There is probably a ScrollViewer surrounding your ItemPresenter and you need to edit a copy of the ItemsControl template.
WPF ListView TextBlock TextWrapping

Resources