Textblock margin causes out of bounds text - c#

I'm currently trying to create a visual component to have scrolling text (left to right and right to left) - pretty much an html marquee.
I have a grid divided in several columns & rows, and I want to place my component inside one of the grid slots.
The grid (named UIGrid) is generated like this :
for (int i = 0; i < xDivisions; i++)
{
ColumnDefinition newColumn = new ColumnDefinition();
UIGrid.ColumnDefinitions.Add(newColumn);
}
for (int i = 0; i < yDivisions; i++)
{
RowDefinition newRow = new RowDefinition();
UIGrid.RowDefinitions.Add(newRow);
}
The component I'm adding is just a border with a textblock as a child. I place the border inside the Grid like this :
border = new Border();
Grid.SetColumn(border, xPosition);
Grid.SetRow(border, yPosition);
textBlock = new TextBlock();
border.Child = textBlock;
textBlock.Text = "Scrolling text from left to right";
UIGrid.Children.Add(border);
I'm using a timer to increment the textblock margin, here's the timer callback simplified body :
textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
double textWidth = textBlock.DesiredSize.Width;
double visibleWidth = componentBase.ActualWidth;
double targetMargin = textWidth < visibleWidth ? visibleWidth : textWidth;
if (margin.Left == targetMargin)
{
margin.Left = -textWidth;
} else
{
margin.Left++;
}
When the text slides from left to right, it behaves nicely :
https://s10.postimg.org/p0nt7vl09/text_good.png
Text "leaving" the grid slot is hidden.
However, when I set the textblock's margin as negative so it may come back inside the viewable area from the left, the text is visible even though it's outside its allocated slot :
https://s10.postimg.org/pownqtjq1/text_bad.png
I've tried using padding instead, but I can't set a negative padding. I've tried a few other things, but I feel like I've encountered a roadblock.
What could I do to get a nicely scrolling text ?

If you want nicely scrolling text ListView might be a better option. It is dynamic and you can bind it to your object. It would take a lot of this guess work out.

Ed Plunkett led me in the right direction with the Clip property. The idea is to do this :
border.Clip = new RectangleGeometry
{
Rect = new Rect(0, 0, border.ActualWidth, border.ActualHeight)
};
Of course, that doesn't work if the border hasn't been rendered yet (and of course it isn't when my code is running). You can force the measurement to take place using 'Measure' as I did to measure the text length in pixels, but it behaved strangely on my border. I wouldn't get the correct size at all.
In the end, I simply subscribed to the border's SizeChanged event :
border.SizeChanged += OnSizeComputed;
When that event is fired, I create the RectangleGeometry using ActualWidth & ActualHeight.

Related

I don't understand how to use the Margin property in WinForms (Windows Forms) applications

Can anyone help me to understand the usefulness of the Margin property?
Using the simple scenario below, I can't see how it's useful
SET UP
I created a simple app to test this:
Created a new WinForms app from the template
Opened Form1 in the designer
Added a 'Panel' (called Panel1) onto Form1 from the toolbox, with:
Dock = Fill;
Size.Width = 800px;
Size.Height = 450px`;
Added two child 'Panels' onto Panel1
Panel2 has Dock = Left
Panel3 has Dock = Right
Both Panel2 and Panel3 have Size.Width = 400px, Size.Height = 450px (so Panel2 and Panel3 effectively split Panel1 into 2 down the middle)
WHY THE PADDING PROPERTY MAKES SENSE TO ME:
The usefulness of Padding is obvious in the designer - it enforces space between the border of the parent (Panel1) and its contents (Panel2 and Panel3)).
So if I set Panel1.Padding.All = 10, then the Size.Height of both Panel2 and Panel3 is forced to decrease (by 20px) to 430px.
Their Size.Width stays the same (they just become overlapped).
Winforms then prevents the Size.Height of Panel2/Panel3 from being increased above 430px, as this would encroach into the padding space of Panel1.
This all makes sense to me
WHY THE MARGIN PROPERTY DOES NOT MAKE SENSE TO ME
Margin is the space around the border of an element - it keeps other elements from getting too close to the element you're setting the Margin on.
So I thought that if I set Margin.Right (on Panel2) to 10px, this would force the Size.Width of Panel3 to decrease (so that it wasn't encroaching on the margin of Panel2).
Instead, setting this right margin appears to have no visible impact on the form?
The Margin property is primarily used by the visual designer and reflected with "snaplines" when positioning controls on the design surface.
See this walkthrough from Microsoft.
One way to think about it (generally) is that Margin is something that happens outside the control whereas Padding is something that happens inside. Also, the "total" effect can be the result of the parent's padding added to the margin of the child control.
The MainForm has padding of 25 (shown in blue) and contains a FlowLayoutPanel set to Dock.Fill. To avoid confusion, the padding and margin of the flow layout panel is set to 0.
The 6 child controls of the flow layout panel set their own left-top margin to 10 and bottom margin to 40. At the top left and the bottom of each child the BackColor of LightSalmon shows through. There is a total of 50 from the bottom of one child to the top of the next one below. Each child control also sets its padding value to 15 which will apply on all four sides of the buttons it contains.
The padding and margin of Button are also set to 0. The the button is auto-sized and centered because it is anchored on all sides.
public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
// Main form Padding in light blue
BackColor = Color.LightSkyBlue;
Padding = new Padding(25);
flowLayoutPanel.BackColor = Color.LightSalmon;
// Set these to 0 and let the individual controls
// manage the padding and margins.
flowLayoutPanel.Margin = new Padding(all: 0);
flowLayoutPanel.Padding = new Padding(all: 0);
for (int i = 1; i <= 6; i++)
{
var panel = new TableLayoutPanel
{
Name = $"panel{i}",
Size = new Size(200, 100),
// Margin 'outside' the panel will show in Light Salmon.
// This will space the panels inside the FlowLayoutPanel
Margin = new Padding(left: 10, top: 10, right: 0, bottom: 40),
// The button inside this panel will have Padding around it.
Padding = new Padding(all: 15),
BackColor = Color.LightGreen,
BackgroundImage = new Bitmap(
Path.Combine(
AppDomain.CurrentDomain.BaseDirectory,
"Images",
"back-image.png"
)),
BackgroundImageLayout = ImageLayout.Stretch,
};
// Add button to internal panel
var button = new Button
{
Name = $"button{i}",
Text = $"Button {(char)(64 + i)}",
BackColor = Color.DarkSeaGreen,
ForeColor = Color.WhiteSmoke,
// By anchoring the button, it will autosize
// respecting the Padding of its parent.
Anchor = AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right | AnchorStyles.Bottom,
Margin = new Padding(all: 0),
Padding = new Padding(all: 0),
};
panel.Controls.Add(button);
flowLayoutPanel.Controls.Add(panel);
}
}
}

WinForms Button: Autosize Maximumsize

I want to add Buttons to a FlowLayoutPanel. The Buttons might contain longer texts with spaces between the words. The Buttons are Autosize=true and AutoSizeMode = AutoSizeMode.GrowAndShrink. Further more I set the MaximumSize property to (maxwidth,0). maxwidth is the width of the panel. So the button does not grow too wide.
What I see is, that the widht of the Button is limited by the MaximumSize property, but when text wrapping occurs, the Button's height doesn't autosize to the height of the wrapped text. Is there a solution to that problem?
I also tried this manually sizing the button like this:
using (Graphics cg = this.CreateGraphics()) {
SizeF size = cg.MeasureString(button.Text, button.Font, 200);
button.Width = (int)size.Width+20;
button.Height = (int)size.Height+20;
button.Text = someLongTextWithSpaces;
}
But please note that I added 20 to the calculated size. It's working, but is there a proper way to determin this additional size? Maybe 2x Padding + ?????
A few hours later...
I came to this version which seems to work quite fine.
using (Graphics cg = this.CreateGraphics()) {
var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
var prop = new Size(tableLayoutPanel1.Width - 20, 0);
var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
int border = button.Height - button.Font.Height;
button.Width = (int)size.Width + border;
button.Height = (int)size.Height + border;
button.Text = someLongTextWithSpaces;
}
It seems that the initial button height is borders + the height the font. So I calculated the border subtracting button.Height-button.font.Height.
According to Hans, I now use the TextRenderer.MeasureText. I tested it without enabling VisualStyles and it worked fine. Any comments on that?
There is a proper way, but it isn't exactly very subtle. Reverse-engineering it from the ButtonRenderer class source code, the Winforms class that draws the button text, you must use the TextRenderer class to measure the text. And you must use the VisualStyleRenderer.GetBackgroundContentRectangle() method to obtain the effective drawing bounds. Note that it is smaller than the button's Size because of the border and a margin that depends on the selected visual style.
Non-trivial problems are mapping a calculated content rectangle back to the outer button size and dealing with old machines that don't have visual styles enabled. Sample code that appeared to arrive at the correct size:
private static void SetButtonSize(Graphics gr, Button button) {
VisualStyleElement ButtonElement = VisualStyleElement.Button.PushButton.Normal;
var visualStyleRenderer = new VisualStyleRenderer(ButtonElement.ClassName, ButtonElement.Part, 0);
var bounds = visualStyleRenderer.GetBackgroundContentRectangle(gr, button.Bounds);
var margin = button.Height - bounds.Height;
var fmt = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.WordBreak;
var prop = new Size(bounds.Width, 0);
var size = TextRenderer.MeasureText(button.Text, button.Font, prop, fmt);
button.ClientSize = new Size(button.ClientSize.Width, size.Height - margin);
}
protected override void OnLoad(EventArgs e) {
using (var gr = this.CreateGraphics()) {
SetButtonSize(gr, this.button1);
}
base.OnLoad(e);
}
Not extensively tested for corner cases, can't say I recommend this.
It seems that the initial button height is borders + the height the font. So I calculated the border subtracting button.Height-button.font.Height. (See the last block of my original post)
This also works with VisualStyles enabled/disabled.
You should control the line breaks by adding newline characters in the text. Automatic text wrapping won't work with spaces alone:
button1.Text = "123232131232\r\nfgfdgfdgdfgdfgdf\r\nASDSADSDASD";
Or :
button1.Text = "123232131232" + Environment.NewLine +
"fgfdgfdgdfgdfgdf" + Environment.NewLine + "ASDSADSDASD";
If you'd rather get the automatic wrapping you could try to use TextMeasure to determine the height needed for the text and then set the button's height accordingly but that may need some extra attention..
But I suggest to consider using Labels instead. For a Label the wrapping works out of the box.. Huge Buttons with varying sizes are non-standard UI elements.

How can i calculate the distance from the top of pictureBox1 and almost the top of form1?

I have a label with text inside i can change the label size or the label font size each time and check many times but maybe there is a way to calculate it:
label18.Text = "מכם מזג האוויר איננו פעיל כרגע";
This is how i see the text now:
The text in red is in hebrew this is the text i want to change it's size and also to put it in the middle according to the picturebox1 top not on the left like it is now.
And i did a black circle just to show what i mean by " the distance from the top of pictureBox1 and almost the top of form1 ".
I mean this gray area from the above the pictureBox1 and the form1 white area on the top only this gray area i want to make the text in this height and in the middle.
How can i calculate this two values ?
I tried this but it's not in the exact middle:
SizeF size = label18.CreateGraphics().MeasureString(label18.Text, label18.Font);
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = pictureBox1.Top - 20;
You don't need graphics or to measure anything. Just set in designer text align = middlecenter and autosize = true
label18.Location = new Point(pictureBox1.Location.X + (pictureBox1.Width / 2 - label18.Width / 2,
pictureBox1.Location.Y - label18.Height);
To center a label you need it get it actual size, then to center it using another control use some simple math to get the coordinate for the control (see below Example 1). I don't know what control the grey bar is but you could center in that by using the size.Width property and doing the same type of calculation.
If you want to fill the grey bar I have added Example 2.
Example 1:
private void CenterLabel()
{
//get the size of the text (you could do this before hand if needed)
SizeF size = label18.CreateGraphics().MeasureString(label18.Text, label18.Font);
//center over picture box control and slightly above
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = pictureBox1.Top - 20;
}
Example 2
private void CenterLabel()
{
int fontHeightPixels = (int)(greyBar.Height * .85);
Font font = new System.Drawing.Font("Arial", fontHeightPixels, FontStyle.Regular, GraphicsUnit.Pixel);
string text = "I am centered";
//get the size of the text (you could do this before hand if needed)
SizeF size = label18.CreateGraphics().MeasureString(text, font);
label18.Font = font;
label18.Text = text;
//center over picture box control and slightly above
label18.Left = (pictureBox1.Width / 2) - (((int)size.Width) / 2) + pictureBox1.Left;
label18.Top = (greyBar.Height / 2) - (((int)size.Height) / 2) + greyBar.Top;
}
This is relatively simple with Windows forms:
Dock your label to the top of the form by setting the appropriate property in the Forms designer. The property you want to set is Dock and it should be set to Top.
Change the label's AutoSize property to false.
Change the label's height as desired.
Change the label's TextAlign property to MiddleCentre.
That should do it.
There's more then one way to achieve this goal.
I would suggest the following:
First calculate the width of the picturebox (picturebox.Width)
Find the coordinates on the form where the picturebox resides (picturebox.Location) property of the picturebox)
Then you change the location of your label control --> to Label.Location.X = (picturebox.Width /2) and Label.Location.Y = picturebox.Location.Y ==> now you have the label correctly placed .
Next Set the Height of the Label Control to the Top(distance between the edge of the form and picturebox) value of the Picturebox.
No visual studion from where i am typing so cannot do full code example.
You're done.

WPF printing/xps issue

I have written the following chunk of code that prints my ListBox perfectly when being sent to a physical printer, however when trying to send it to the XPS printer driver or using the XpsDocumentWriter class (I assume they use the same code under the hood) I receive the following exception:
System.ArgumentException was unhandled by user code
Message=Width and Height must be non-negative.
Source=ReachFramework
StackTrace:
at System.Windows.Xps.Serialization.VisualSerializer.WriteTileBrush(String element, TileBrush brush, Rect bounds)
The exception obviously points to an item not having a correct width/height however I have debugged the code when sending it to the different printers (physical and XPS driver) and I haven't been able to find any differences.
Below is how I create the visual to send to the printer:
private ScrollViewer GeneratePrintableView()
{
ScrollViewer scrollView = new ScrollViewer();
Grid grid = new Grid { Background = Brushes.White, Width = this.myListBox.ActualWidth, Height = this.myListBox.ActualHeight };
grid.RowDefinitions.Add(new RowDefinition());
grid.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Auto);
grid.RowDefinitions.Add(new RowDefinition());
grid.RowDefinitions[1].Height = new GridLength(0, GridUnitType.Auto);
// Add the title and icon to the top
VisualBrush titleClone = new VisualBrush(this.TitleBar);
var titleRectangle = new Rectangle { Fill = titleClone, Width = this.TitleBar.ActualWidth, Height = this.TitleBar.ActualHeight };
grid.Children.Add(titleRectangle);
Grid.SetRow(titleRectangle, 0);
this.myListBox.Width = this.myListBox.ActualWidth;
this.myListBox.Height = this.myListBox.ActualHeight;
VisualBrush clone = new VisualBrush(this.myListBox) { Stretch = Stretch.None, AutoLayoutContent = true };
var rectangle = new Rectangle { Fill = clone, Width = this.myListBox.ActualWidth, Height = this.myListBox.ActualHeight };
Border border = new Border { Background = Brushes.White, Width = this.myListBox.ActualWidth, Height = this.myListBox.ActualHeight };
border.Child = rectangle;
grid.Children.Add(border);
Grid.SetRow(border, 1);
scrollView.Width = this.myListBox.ActualWidth;
scrollView.Height = this.myListBox.ActualHeight;
scrollView.Content = grid;
scrollView.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden;
return scrollView;
}
Here is the GetPage override in my DocumentPaginator implementation:
public override DocumentPage GetPage(int pageNumber)
{
Page page = new Page();
double z = 0.0;
this.grid = new Grid();
this.grid.RowDefinitions.Add(new RowDefinition());
this.grid.RowDefinitions[0].Height = new GridLength(0, GridUnitType.Auto);
this.grid.Children.Add(this.printViewer);
Grid.SetRow(this.printViewer, 0);
//Adjusting the vertical scroll offset depending on the page number
if (pageNumber + 1 == 1) //if First Page
{
this.printViewer.ScrollToVerticalOffset(0);
this.printViewer.UpdateLayout();
}
else if (pageNumber + 1 == _verticalPageCount) //if Last Page
{
if (this.printViewer.ScrollableHeight == 0) //If printing only single page and the contents fits only on one page
{
this.printViewer.ScrollToVerticalOffset(0);
this.printViewer.UpdateLayout();
}
else if (this.printViewer.ScrollableHeight <= this.printViewer.Height) //If scrollconentheight is less or equal than scrollheight
{
this.printViewer.Height = this.printViewer.ScrollableHeight;
this.printViewer.ScrollToEnd();
this.printViewer.UpdateLayout();
}
else //if the scrollcontentheight is greater than scrollheight then set the scrollviewer height to be the remainder between scrollcontentheight and scrollheight
{
this.printViewer.Height = (this.printViewer.ScrollableHeight % this.printViewer.Height) + 5;
this.printViewer.ScrollToEnd();
this.printViewer.UpdateLayout();
}
}
else //Other Pages
{
z = z + this.printViewer.Height;
this.printViewer.ScrollToVerticalOffset(z);
this.printViewer.UpdateLayout();
}
page.Content = this.grid; //put the grid into the page
page.Arrange(new Rect(this.originalMargin.Left, this.originalMargin.Top, this.ContentSize.Width, this.ContentSize.Height));
page.UpdateLayout();
return new DocumentPage(page);
}
Interestingly if I change the Fill of rectangle to a Brush instead of clone then I do not receive the exception and the outputted file is the correct size.
I have spent over a day trying to debug why this isn't working and I am hoping that someone out there has either seen a similar issue or is able to point out any mistakes I am making.
Thanks for any responses.
I had to give up finding a solution with VisualBrush. If there is a GroupBox in the Visual for the brush I could never get it to produce a XPS file. It always fails with
System.ArgumentException was unhandled by user code Message=Width and Height must be non-negative. Source=ReachFramework StackTrace: at System.Windows.Xps.Serialization.VisualSerializer.WriteTileBrush(String element, TileBrush brush, Rect bounds)
The workaround was to clone the content that should go in the VisualBrush (Is there an easy/built-in way to get an exact copy (clone) of a XAML element?) and use that directly in a Grid instead of an VisualBrush
Have you checked the value of ActualWidth and ActualHeight of myListBox when the VisualBrush is being created? I don't know from where myListBox comes, but if it is not rendered by the time you are generating your xps document you may run into problems. You can try to manually force the control to render and see if it makes any difference.
I was unable to rectify the problem however using this link Paginated printing of WPF visuals I was able to find a suitable solution to allow printing of complicated visuals within my WPF application.
It's 2016 now and it's still not fixed. The problem is using TileBrush or any descendant type (VisualBrush in your case). If you use absolute mapping, it works, it's the relative mapping that causes the problem. Calculate the final size yourself and set Viewport to this size, ViewportUnits to Absolute. Also make sure you don't use Stretch.

how to get a labels width before it is rendered in WPF

Tricky one to explain this. I have a custom built properties grid. The left hand column has the property labels. Sometimes depending on the property, I want a little elipsis button to show the user that they can launch a dialog. I want the buttons to be inline vertically to make the UI look neat. The labels vary in width depending on the name of the property "onEnterPressed" or "upLink" for example.
If I add the elipses button alone and use a margin like so ...
elipsisButton.Margin = new Thickness(135, 0, 0, 0);
135 from the left is exactly where I want to place the button.
I was hoping to be able to do something like
Label newLabel = new System.Windows.Controls.Label();
newLabel.Content = anInfo;
aPanel.Children.Add(newLabel);
elipsisButton.Margin = new Thickness(135 - newLabel.Width, 0, 0, 0);
It would appear however, that the label doesn't get a width until it's been rendered on screen so I can't find out what size margin to add to my elipsis button. Any ideas?
You can call the Measure() method in order to ask the control the size it needs to be displayed:
var l = new Label() { Content = "Hello" };
l.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
Size s = l.DesiredSize;
And then use the value of the DesiredSize property.

Categories