Can I know width of TextBlock when create it? - c#

I create TextBox on the Canvas like this:
TextBlock t = new TextBlock();
t.Foreground = new SolidColorBrush(...);
t.FontSize = 10;
t.HorizontalAlignment = HorizontalAlignment.Left;
t.VerticalAlignment = VerticalAlignment.Top;
t.Text = ...;
Canvas.SetLeft(t, "f(width)");
Canvas.SetTop(t, ...);
canvas.Children.Add(t);
I want to know width of this TextBlock, because Left coordinate depends on this.
Can I do it? ActualWidth is 0.
Thanks.

Before you add it, call Measure on it, then use the DesiredSize.
Edit: This is OK to do because Canvas does not affect the size of the element once placed. If you added it to, say, a Grid with a fixed-size row, this wouldn't give you the real Height once added since the adding to the Grid would change it.
As Mario Vernari points out, if you have real complex positioning needs it's pretty easy to override ArrangeOverride (and sometimes MeasureOverride) and make a custom panel. Canvas is actually written this way, as is StackPanel, etc. They are all just specific-measuring and arranging panels, and you can make your own, too.

Related

WrapPanel creates a new column for each dynamically expanding control

I have a vertical WarpPanel that is populated with controls at runtime. The types and number of controls is determined at runtime. It works good with controls that have a fixed height, but controls that expand according to their contents (e.g. Listbox) often create a new column. I somehow need to force the panel to place the controls in the last column as the other, fixed height controls UNLESS the space available in the column is less than MinHeight of the control we are trying to place. Setting Height or MaxHeight for the controls is not an option.
The image below demonstrates the problem. The two listboxes' widths are the same, but instead of putting them in the same column, one of them ends up half-invisible.
Instead of that I would expect to get this:
Is there any way to implement this without making/using a custom panel?
Code:
**Panel:**
<WrapPanel x:Name="wp" Orientation="Vertical">
**Adding controls:**
private void AddControl(bool isListBox)
{
if (isListBox)
{
var lb = new ListBox();
lb.MinHeight = 310;
lb.Width = 310;
lb.MaxWidth = 310;
lb.MinWidth = 310;
wp.Children.Add(lb);
}
else
{
var cb = new ComboBox();
cb.Width = 310;
cb.MaxWidth = 310;
wp.Children.Add(cb);
}
}
The problem here is that the WrapPanel is always going to give the ListBox as much space as it wants, up to the available height in the WrapPanel. What you want to have happen is something more like a UniformGrid effect, but only for expanding Height elements in the column and only as long as the MinHeight constraint isn't violated. This gets a bit tricky, especially if you have other fixed height elements in-between the ListBox elements or other elements with different MinHeight constraints.
It's possible to do the computation, but I think you'll need to create a custom Panel to get this behavior. Basically, it would work like the WrapPanel code, but when you have variable height elements (elements whose Measure returns unbounded size in the wrap dimension), it needs to look at their MinHeight and accumulate these with the fixed Height elements in the same column, ultimately dividing the remaining non-fixed Height by the number of variable elements, to produce the height(s) that will be provided in the Arrange pass.

Animate a label

I am trying to animate a label in a WPF application. The label gets created programatically (and dynamically) so it is not defined in XAML, but is created in the C# code.
Animation Story
The label appears in the bottom of the window. The label should be positioned lower than the window, so the user can not see it initially. Then a the label moves up (like sliding) and fades out before it reaches the top of the window.
What I have done
I have implemented this behavior myself in an other project. This time I want to use WPF which should perform better.
So far I have seen there should be multiple ways of doing this. Starting with a DoubleAnimation, going by a PathAnimation and VectorAnimation (the last of which I have not tested successfully).
Encountered problems
The animation works nice with a DoubleAnimation, but there is a problem: When I resize the window, the label gets resized too (similar to an anchor in Winforms). When I make the window smaller the label gets smaller too, until it disappears completely. This effect occurs only in the height of the label. I added the code snippet adding the label. Maybe you find some error. Also there should be a better way to implement this (I personally find it very ugly).
Label lbl = new Label()
{
Content = "Test",
FontSize = 36,
Foreground = new SolidColorBrush(Colors.Red),
Background = new SolidColorBrush(Colors.Black),
HorizontalContentAlignment = System.Windows.HorizontalAlignment.Center,
VerticalAlignment = System.Windows.VerticalAlignment.Top
};
lbl.Margin = new Thickness(0, this.MainGrid.ActualHeight + lbl.ActualHeight, 0, 0);
this.MainGrid.Children.Add(lbl);
UpdateLayout();
Transform myTransform = new TranslateTransform();
lbl.RenderTransform = myTransform;
DoubleAnimation AnimationY = new DoubleAnimation((this.MainGrid.ActualHeight + 20) * -1, TimeSpan.FromSeconds(4));
myTransform.BeginAnimation(TranslateTransform.YProperty, AnimationY);
Questions
As I said, I have found multiple ways that seem to achieve the same behavior. Which one could I use to do this. I still have to do the fade-out on the top of the window, but this animation is easier to do compared to the movement.
The animation is fine. The reason your label is resizing is because you are adding it to a Grid. If you want your label to have a fixed height, then set its Height or MinHeight property.

Drawing a chart in WPF C# design questions

I had a project a month ago where I drew a stock chart in an application using Windows Forms. I did this by creating a bitmap that would stretch to the dimensions of the window. This would allow my chart to resize with the window.
I am now expanding the project using WPF. I have been trying to work on my design for the project, but I cant seem to get any idea on the best way to do the same chart. I have looked at canvases, grids, and a few other controls. I thought I was on the right track with the canvas, but when I would resize the window, my drawing would stay in the same spot. I guess the point of my post tonight is to get some ideas to help me brainstorm a design for my project.
All advice and questions are appreciated.
Thanks,
Joseph
(Realizing this addresses at best a subset of this fairly old question, since it's only one chart type...)
Just fwiw, creating a bar graph in a Grid as Ed suggests is pretty straightforward. Here's a quick and dirty version:
Add a Grid to your Window's XAML. Just for testing, here's one that fills the Window entirely.
<Grid>
<Grid
Name="myGrid"
HorizontalAlignment="Stretch"
VerticalAlignment="Stretch"
Width="auto"
Height="auto"
Margin="10,10,10,10"
/>
</Grid>
Now insert these two utility functions somewhere in your project. These provide simple, single-color columns and unstyled, but centered, label text for the x-axis.
I think the only nasty kludge is the maxHeight in the _placeSingleColorColumn call.
Worth mentioning: I don't have labels for the y-axis in this quick & dirty version.
private void _placeSingleColorColumn(Grid grid, Color color, int height, int colNum, int maxHeight)
{
Brush brush = new SolidColorBrush(color);
Rectangle rect = new Rectangle();
rect.Fill = brush;
Grid.SetColumn(rect, colNum);
Grid.SetRow(rect, maxHeight - height);
Grid.SetRowSpan(rect, height);
grid.Children.Add(rect);
}
private void _createLabels(Grid grid, string[] labels)
{
RowDefinition rowDefnLabels = new RowDefinition();
grid.RowDefinitions.Add(rowDefnLabels);
for (int i = 0; i < labels.Length; i++)
{
TextBlock block = new TextBlock();
block.Text = labels[i];
block.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
Grid.SetColumn(block, i);
Grid.SetRow(block, grid.RowDefinitions.Count);
grid.Children.Add(block);
}
}
That's really it. Here's some insanely quickly and dirty example code to create a 10 by 10 grid with some sample data.
public void createGrid10x10()
{
Random random = new Random();
for (int i=0; i<10; i++)
{
ColumnDefinition colDef = new ColumnDefinition();
myGrid.ColumnDefinitions.Add(colDef);
RowDefinition rowDef = new RowDefinition();
myGrid.RowDefinitions.Add(rowDef);
Color color = i % 2 == 0 ? Colors.Red : Colors.Blue;
_placeSingleColorColumn(this.myGrid, color, random.Next(1,11), i, 10);
}
string[] aLabels = "Dogs,Cats,Birds,Snakes,Rabbits,Hamsters,Horses,Rats,Bats,Unicorns".Split(',');
_createLabels(this.myGrid, aLabels);
}
Add one line to your MainWindow constructor, and you're done, afaict.
public MainWindow()
{
InitializeComponent();
this.createGrid10x10();
}
Now you've got a bar graph that'll resize and stay proportional as the window is resized, etc.
Adding more labels (bar values on top, y-axis labels, etc) should be pretty straightforward if you understand the above. Just throw in another column and/or row, create your TextBlocks, and place them in the right locations.
Try using a DockPanel and set LastChildFill to true. Then make your control the last child of the DockPanel.
Funny: I am just making the same thing!
I already developed a chart control, plenty of features. Now I need to renew and extend it with some other function. However, my deal is manage even 100k of points on a single chart, but keeping a good performance on a normal pc. By resizing the window will scale the chart, but not the text eventually placed on it. Also consider that I need a real-time rendering of the data incoming at least 0.5 sec.
All that has been resolved using the old-style bitmap creation, then placing it as a normal image on any wpf control. There are several limitation because there's no "living" objects as in the wpf you have, but the rendering performance is really huge compared to the wpf primitives.
So, unless you have charts with max 100 points to manage, I strongly recommend the hybrid approach. Anyway, it's a very hard task!
Cheers
I am assuming you want to draw your own chart rather than using WPF charts.
Canvas is not usually a good thing to use in WPF because it fixes objects at a specific location and size, exactly as you've seen (though I suppose you could use a Canvas with a ScaleTransform). Grid will take the size of its container, so putting a Grid into a window will make the Grid resize with the window (unless you specify a fixed Width and Height for the Grid). StackPanel will stack things and will attempt to take the minimum size of its content, so that's probably not what you want to use here.
Creating a chart layout inside a panel like a Grid isn't completely simple. If you are doing a bar chart, you could create a Column in the Grid for each bar, assign a percentage width such as star; and the columns would get larger as your Grid expanded with the window. You can use a similar trick by making each Bar a Grid, setting two columns in the Grid, and setting a third level of Grid inside the lowest column, then using percentages for the column heights (e.g., 90star and 10star for 90%, 10% heights). The bars would then grow taller as the window grows taller. You could reserve a Grid row below the bars for labels, and center them under the bars.
Line charts are trickier. You would probably want to create a GeometryDrawing of line segments, and then use a ScaleTransform bound to the window size to make it shrink and grow.
There are a lot of possibilities with WPF, but you'll need to do a bit of leaning and studying first. A book such as Adam Nathan's "Windows Presentation Foundation Unleashed" would quickly give you a lot of knowledge of WPF layout and how to proceed.
Edit: You could also use an empty panel and use its DrawingContext to draw lines, rectangles, text, ellipses, etc. at points you calculated from the current window size.

How to add content control to a shape added to a canvas all runtime

I have a static canvas. I have added a shape runtime. Then I try to add a contentcontrol which will hold the shape. But as the the shape is already added to the canvas, it gives a logical child error.
Can anyone help me how to get this done keeping the logic of adding the contentcontrol later dynamically?
XAML:
Inside window tag keep a blank canvas with name="cnv"
C#:
Ellipse ee = new Ellipse();
ee.Width = 100;
ee.Height= 50;
ee.Fill= Brushes.Red;
ee.Name = "el";
hidden.Children.Add(ee);
ContentControl cc = new ContentControl();
cc.BorderBrush = Brushes.Black;
cc.Content = ee;
cnv.Children.Add(ee);
As Kent points out an element can only have one parent, so simply remove the line:
hidden.Children.Add(ee);
from your code as you are also calling:
cnv.Children.Add(ee);
A UIElement can only have one parent, so you'll need to remove it from the Canvas before re-seating it elsewhere:
hidden.Children.Remove(ee);
cc.Content = ee;
cnv.Children.Add(ee);
PS. There's almost certainly a nicer, cleaner way to do whatever it is you're trying to do, rather than playing around in the visual tree like you are.

FlowLayoutPanel autowrapping doesn't work with autosize

.NET Framework / C# / Windows Forms
I'd like the FlowLayoutPanel to automatically adjust its width or height depending on number of controls inside of it. It also should change the number of columns/rows if there is not enough space (wrap its content). The problem is that if I set autosize then the flowlayoutpanel doesn't wrap controls I insert. Which solution is the best?
Thanks!
Set the FlowLayoutPanel's MaximumSize to the width you want it to wrap at. Set WrapContents = true.
Have you tried using the TableLayoutPanel? It's very useful for placing controls within cells.
There is no such thing like impossible in software development. Impossible just takes longer.
I've investigated the problem. If there is really need for Flow Layout, it can be done with a bit of work. Since FlowLayoutPanel lays out the controls without particularly thinking about the number of rows/columns, but rather on cumulative width/height, you may need to keep track of how many controls you've already added. First of all, set the autosize to false, then hook your own size management logic to the ControlAdded/ControlRemoved events. The idea is to set the width and height of the panel in such a way, that you'll get your desired number of 'columns' there
Dirty proof of concept:
private void flowLayoutPanel1_ControlAdded(object sender, ControlEventArgs e)
{
int count = this.flowLayoutPanel1.Controls.Count;
if (count % 4 == 0)
{
this.flowLayoutPanel1.Height = this.flowLayoutPanel1.Height + 70;
}
}
if the panel has initially width for 4 controls, it will generate row for new ones. ControlRemoved handler should check the same and decrease the panel height, or get all contained controls and place them again. You should think about it, it may not be the kind of thing you want. It depends on the usage scenarios. Will all the controls be of the same size? If not, you'd need more complicated logic.
But really, think about table layout - you can wrap it in a helper class or derive new control from it, where you'd resolve all the control placing logic. FlowLayout makes it easy to add and remove controls, but then the size management code goes in. TableLayout gives you a good mechanism for rows and columns, managing width and height is easier, but you'd need more code to change the placement of all controls if you want to remove one from the form dynamically.
If possible, I suggest you re-size the FlowLayoutPanel so that it makes use of all the width that is available and then anchor it at Top, Left and Right. This should make it grow in height as needed while still wrapping the controls.
I know this is an old thread but if anyone else wonders on here then here's the solution I produced - set autosize to true on the panel and call this extension method from the flow panel's Resize event:
public static void ReOrganise(this FlowLayoutPanel panel)
{
var width = 0;
Control prevChildCtrl = null;
panel.SuspendLayout();
//Clear flow breaks
foreach (Control childCtrl in panel.Controls)
{
panel.SetFlowBreak(childCtrl, false);
}
foreach (Control childCtrl in panel.Controls)
{
width = width + childCtrl.Width;
if(width > panel.Width && prevChildCtrl != null)
{
panel.SetFlowBreak(prevChildCtrl, true);
width = childCtrl.Width;
}
prevChildCtrl = childCtrl;
}
panel.ResumeLayout();
}
Are you adding the controls dynamically basing on the user's actions? I'm afraid you'd need to change the FlowLayout properties on the fly in code, when adding new controls to it, then refreshing the form would do the trick.

Categories