WPF Grid Column MaxWidth not enforced - wpf

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

Related

How to use Textwrap property without defining the width in windows phone development?

I am using a grid with single row. I have placed a single LongListSelector within that row. The ItemTemplate is as follows,
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition/>
</Grid.RowDefinitions>
<!--when we dont mention any of the height and width properties then control tries to first occupy the minimum height/width required and then it streches to the extent it is possible-->
<phone:LongListSelector Grid.Row="0" x:Name="CLASS1">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Margin="25,20" Background="#FF616464" Width="Auto">
<TextBlock Text="{Binding title, Mode=TwoWay}" FontSize="40" Margin="20,20" Foreground="White" TextAlignment="Left" TextWrapping="Wrap" FontStyle="Normal" FontFamily="Segoe UI"/>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
Now I know that if we don't mention the width,MaxWidth values in the XAML file or in the properties, the Textblock above will stretch itself to the width it really needs to fit in the text. If there still some more width remaining it will expand till that extent. However I want to wrap the text of the Textblock. At the same time I want to utilize all the width available for stretching the TextBlock. So basically I want that the Textblock to stretch itself using the maximum width available and if the Text within it is still longer then I want to wrap it. Is there any solution to achieve this. I can use text wrap by setting constant value for width. As I want to deploy this application on different models then can I make it generic? Is there anyway to use parent's width?
All you have to do is to replace StackPanel with Grid.
<DataTemplate>
<Grid Margin="25,20" Background="#FF616464" Width="Auto">
<TextBlock Text="{Binding title, Mode=TwoWay}" FontSize="40" Margin="20,20" Foreground="White" TextAlignment="Left" TextWrapping="Wrap" FontStyle="Normal" FontFamily="Segoe UI"/>
</Grid>
</DataTemplate>
Result:
try this property
HorizontalContentAlignment="Stretch"

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 TextBox Wrapping

I am trying to figure out how to get a textbox to wrap its contents, however the situation isn't quite the same as the typical "it doesn't wrap" scenario. My textbox is contained inside a DataTemplate which is used inside a Telerik RadTabControl instance (using a ContentTemplatePresenter to determine which view to display) and the XAML for the DataTemplate looks like this:
<DataTemplate x:Key="NotesTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Use the box below to record any general notes associated with this item." Style="{StaticResource Default}" />
<TextBox TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" GridRow="1" Margin="20" Text="{Binding Notes, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</DataTemplate>
The reason I say it doesn't fall under the normal "it doesn't wrap" scenario is it used to wrap until I had to change the view to be resizable to anything to support the varying screen sizes the app will be run on. When I did that the TextBox stopped wrapping because (presumably) as the user types something the TextBox says "I need more space" so the parent obliges and the box continues out to the right indefinitely (although the view gets scrollbars). I tried setting a MaxWidth using Binding/RelativeSource, but since the parent is specifically designed to grow that approach won't work. What I need to have happen is the box should be the width of its' containing parents' VisibleWidth. Meaning, if the Window itself is 1024x768, the TextBox's MaxWidth should be 1024 and any text thereafter would automatically wrap, but if the Window grows to 1280x1024 the box should now be 1280 and the text wrap accordingly. I tried this scenario with this binding expression, but no luck:
MaxWidth="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Window}}, Path=ActualWidth}"
The Window size itself isn't growing so if I could get the Window's Width (minus a certain amount to cover the width of the tabs that are part of the TabControl) I believe that would work.
Any ideas?
although the view gets scrollbars
Disable the horizontal scrollView, so it will be forced to wrap. You can try to disable it on the TextBox itself, or on the wrapping Grid.
<DataTemplate x:Key="NotesTemplate">
<Grid ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Text="Use the box below to record any general notes associated with this item." Style="{StaticResource Default}" />
<TextBox TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" Grid.Row="1" Margin="20" Text="{Binding Notes, UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</DataTemplate>

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.

Resources