How to force ActualWidth and ActualHeight to update (silverlight) - silverlight

I a grid on my silverlight control, I am programatically adding a canvas, and in the canvas I am loading and displaying Image.
I'm also adding a rotation to the canvas. The problem is that by default the CenterX and CenterY of the rotation is the top left of the canvas. What I want is the rotation to happen around the centre of the canvas.
To do this, I've tried setting the CenterX and CenterY of the Rotation to the Images ActualWidth / 2 and ActualHeight / 2, however I've discovered that ActualWidth and ActualHeight are not always populated, at least not right away. How can I force them to get updated?
Even using the DownloadProgress event on the image doesn't seem to guarantee the ActualWidth and ActualHeight are populated, and neither does using this.Dispatcher.BeginInvoke()...
Image imgTest = new Image();
Canvas cnvTest = new Canvas();
Uri uriImage = new Uri("myurl", UriKind.RelativeOrAbsolute);
System.Windows.Media.Imaging.BitmapImage bmpDisplay = new System.Windows.Media.Imaging.BitmapImage(uriImage);
bmpDisplay.DownloadProgress += new EventHandler<System.Windows.Media.Imaging.DownloadProgressEventArgs>(this.GetActualDimensionsAfterDownload);
imgTest.Source = bmpDisplay;
imgTest.Stretch = Stretch.Uniform;
imgTest.HorizontalAlignment = HorizontalAlignment.Center;
imgTest.VerticalAlignment = VerticalAlignment.Center;
cnvTest.Children.Add(imgTest);
this.grdLayout.Children.Add(imgTest);
this.Dispatcher.BeginInvoke(new Action(GetActualDimensions));

To update the ActualWidth and ActualHeight of a FrameworkElement you will have to call UpdateLayout.

Unfortunately, calling updateLayout doesn't always work either depending on your situation.
I've had better luck doing something like:
whateverUIElement.Dispatcher.BeginInvoke(()
{
//code that needs width/height here
}
);
but even that fails too often.

Most reliable method I found is to use DependencyPropertyDescriptor AddValueChanged listeners of ActualWidth and ActualHeight instead of OnLayoutUpdated to get element sizes after rendering
DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(ActualWidthProperty, typeof(StackPanel));
if (descriptor != null)
{
descriptor.AddValueChanged(uiPanelRoot, DrawPipelines_LayoutUpdated);
}
descriptor = DependencyPropertyDescriptor.FromProperty(ActualHeightProperty, typeof(StackPanel));
if (descriptor != null)
{
descriptor.AddValueChanged(uiPanelRoot, DrawPipelines_LayoutUpdated);
}
void DrawPipelines_LayoutUpdated(object sender, EventArgs e)
{
// Point point1 = elementInstrumentSampleVial.TranslatePoint(
// new Point(11.0, 15.0), uiGridMainInner);
}
Instead of using StackPanel, Grid etc. use base element that you are depending on for relative sizes

Related

Connecting two dynamically created shapes using line shape in silverlight

Im working on flowchart kind of application in asp.net using silverlight.. Im a beginner in Silvelight, Creating the elements (Rectangle,Ellipse,Line.. ) dynamically using SHAPE and LINE Objects in codebehind (c#)
These shapes will be generated dynamically, meaning I'll be calling a Web service on the backend to determine how many objects/shapes need to be created. Once this is determined, I'll need to have the objects/shapes connected together.
how to connect dynamically created shapes with a line in Silverlight like a flowchart.
I read the below article, but its not working for me, actualHeight & actualWidth of shapes values are 0.
Connecting two shapes together, Silverlight 2
here is my MainPage.xaml
<UserControl x:Class="LightTest1.MainPage">
<Canvas x:Name="LayoutRoot" Background="White">
<Canvas x:Name="MyCanvas" Background="Red"></Canvas>
<Button x:Name="btnPush" Content="AddRectangle" Height="20" Width="80" Margin="12,268,348,12" Click="btnPush_Click"></Button>
</Canvas>
code behind MainPage.xaml.cs
StackPanel sp1 = new StackPanel();
public MainPage()
{
InitializeComponent();
sp1.Orientation = Orientation.Vertical;
MyCanvas.Children.Add(sp1);
}
Rectangle rect1;
Rectangle rect2;
Line line1;
private void btnPush_Click(object sender, RoutedEventArgs e)
{
rect1 = new Rectangle()
{
Height = 30,
Width = 30,
StrokeThickness = 3,
Stroke = new SolidColorBrush(Colors.Red),
};
sp1.Children.Add(rect1);
rect2 = new Rectangle()
{
Height = 30,
Width = 30,
StrokeThickness = 3,
Stroke = new SolidColorBrush(Colors.Red),
};
sp1.Children.Add(rect2);
connectShapes(rect1, rect2);
}
private void connectShapes(Shape s1, Shape s2)
{
var transform1 = s1.TransformToVisual(s1.Parent as UIElement);
var transform2 = s2.TransformToVisual(s2.Parent as UIElement);
var lineGeometry = new LineGeometry()
{
StartPoint = transform1.Transform(new Point(1, s1.ActualHeight / 2.0)),
EndPoint = transform2.Transform(new Point(s2.ActualWidth, s2.ActualHeight / 2.0))
};
var path = new Path()
{
Data = lineGeometry,
Stroke = new SolidColorBrush(Colors.Green),
};
sp1.Children.Add(path);
}
what I am doing in button click event is just adding two rectangle shapes and tring to connect them with a line (like flowchart).
Please suggest what is wrong in my code..
Try replacing the line
connectShapes(rect1, rect2);
with
Dispatcher.BeginInvoke(() => connectShapes(rect1, rect2));
I'm not sure of the exact reason why this works, but I believe the shapes are only rendered once control passes out of your code, and only once they are rendered do the ActualWidth and ActualHeight properties have a useful value. Calling Dispatcher.BeginInvoke calls your code a short time later; in fact, you may notice the lines being drawn slightly after the rectangles.
The TransformToVisual method behaves in much the same way as the ActualWidth and ActualHeight properties. It will return an identity transformation if the shape hasn't been rendered. Even if your lines were being drawn with a definite width and height, they would end up being drawn all on top of one another at the top-left.
I also found that I needed to add the lines to the Canvas, not the StackPanel, in order for them to be drawn over the rectangles. Otherwise the StackPanel quickly filled up with lines with a lot of space above them.

unify elements size in stackpanel

I need help in unifying size of elements in stackpanel
void MainPageLoaded(object sender, RoutedEventArgs e)
{
var random = new Random();
for (var i = 0; i < 5; i++)
{
var grid = new Grid();
var border = new Border()
{
Height = random.Next(50, 150),
Width = random.Next(50, 150),
Margin = new Thickness(10),
BorderBrush = new SolidColorBrush(Colors.White),
BorderThickness = new Thickness(1)
};
grid.Children.Add(border);
imageBoxesStackPanel.Children.Add(grid);
}
var h = imageBoxesStackPanel.Children.Max(n => n.DesiredSize.Height);
what I am trying to achieve is to find max height and max width of each grid in stackpanel and apply it to all of them. The problem is that desired size is always wrong.
You can only do this in a custom way after a measure/arrange pass, before that the sizes won't be visible.
After that (in the OnLoaded event, which you have), you can use the ActualHeight and ActualWidth of the grids.
In short:
var h = imageBoxesStackPanel.Children.Max(n => n.ActualHeight);
This is however bad for performance and will trigger another layout pass.
Remarks:
In WPF the best solution would be a SharedSizeGroup or a UniformGrid. This is not implemented in Silverlight, but there are people who have implemented it.
In WPF there is the UniformGrid to do this job, but unfortunately it's not implemented for Silverlight by default. There are several alternatives for it, e.g. this one

How to animate ListBoxItem position

I am having some trouble animating the items in my ListBox. Animations on the OpacityProperty work great but when i try to animate the position of my ListBoxItem it simply does not move an inch (No exceptions are thrown, not even a log message indicating error).
Here is the code i am using:
private void deletAnimation()
{
Todo todoToDelete = App.ViewModel.Todos[1];
Storyboard storyboard = new Storyboard();
DoubleAnimation alphaAnim = new DoubleAnimation();
alphaAnim.From = 1;
alphaAnim.To = 0;
alphaAnim.Duration = new Duration(TimeSpan.FromMilliseconds(500));
ListBoxItem target = TodoList.ItemContainerGenerator.ContainerFromItem(todoToDelete) as ListBoxItem;
Storyboard.SetTarget(alphaAnim, target);
Storyboard.SetTargetProperty(alphaAnim, new PropertyPath(UIElement.OpacityProperty));
storyboard.Children.Add(alphaAnim);
for (int i = App.ViewModel.Todos.IndexOf(todoToDelete) + 1; i < App.ViewModel.Todos.Count; i++)
{
Todo todo = App.ViewModel.Todos[i];
target = TodoList.ItemContainerGenerator.ContainerFromItem(todo) as ListBoxItem;
DoubleAnimation translateAnim = new DoubleAnimation();
translateAnim.From = target.RenderTransformOrigin.Y;
translateAnim.To = target.RenderTransformOrigin.Y - target.ActualHeight;
translateAnim.Duration = new Duration(TimeSpan.FromMilliseconds(500));
translateAnim.BeginTime = TimeSpan.FromMilliseconds(500);
Storyboard.SetTarget(translateAnim, target);
Storyboard.SetTargetProperty(translateAnim, new PropertyPath(TranslateTransform.YProperty));
storyboard.Children.Add(translateAnim);
}
storyboard.Begin();
}
Some things i have noticed while debugging:
The RenderTransformOrigin.Y property is always 0 no matter which ListBoxItem is referenced.
The Height property is NaN though the ActualHeight property is 67
The parent property of the ListBoxItem is null
These two things make me wonder if i am given a reference to a ListBoxItem that is not rendered of the screen? But as the Opacity animation works perfectly and all of my list is visible(only contains 3 items at the moment) i do not see how this could be the case.
I have also tried using a PointAnimation and animating the RenderTransformOrigin property directly but this gave the same result (nothing that is).
Any help is appreciated, thanks!
Please check out this link:
http://blogs.msdn.com/b/jasongin/archive/2011/01/03/wp7-reorderlistbox-improvements-rearrange-animations-and-more.aspx
Someone has created a class that you can easily incorporate into your app. This has animations for adding/removing items from your list.
This should save you a lot of time and frustration.

Flip Horizontically Grid Background Image(Brush)

I have set a Grid's background brush as an ImageBrush.
But when I set the Grid's FlowDirection to RightToLeft, the image is flipped horizontically.
Is it possible to (un)flip the grid background ImageBrush using a certain Transition or any other way?
Not much you can do about that with sensible means (there same means that are far from sensible).
Instead place an Image element as the first item in the Grid with Grid.RowSpan, Grid.ColumnSpan to cover all the cells. Use Stretch="Fill" on the Image since thats how a background typically behaves.
Well, i do understand that my comment is outdated, but this question is popping up one of the first in Google search, so here is my solution:
I was localizing the application for the right-to-left culture. The simple decision to set FlowDirection=RTL comes with unexpected drawbacks like the background containing the company logo is flipped. I have applied the matrix transformation for the image brush used to render the background:
var mbgBrush = TryFindResource("MainBackground") as Brush;
if (mbgBrush == null) return null;
if (FlowDirection == FlowDirection.LeftToRight) return mbgBrush;
var mainBgImageBrush = mbgBrush as ImageBrush;
if (mainBgImageBrush == null) return mbgBrush;
var flipXaxis = new MatrixTransform(-1.0, 0, 0, 1.0, 1, 0);
var flippedBrush = new ImageBrush
{
Stretch = Stretch.None,
Opacity = 1.0,
ImageSource = mainBgImageBrush.ImageSource,
RelativeTransform = flipXaxis
};
return flippedBrush;

WPF - Set dialog window position relative to main window?

I'm just creating my own AboutBox and I'm calling it using Window.ShowDialog()
How do I get it to position relative to the main window, i.e. 20px from the top and centered?
You can simply use the Window.Left and Window.Top properties. Read them from your main window and assign the values (plus 20 px or whatever) to the AboutBox before calling the ShowDialog() method.
AboutBox dialog = new AboutBox();
dialog.Top = mainWindow.Top + 20;
To have it centered, you can also simply use the WindowStartupLocation property. Set this to WindowStartupLocation.CenterOwner
AboutBox dialog = new AboutBox();
dialog.Owner = Application.Current.MainWindow; // We must also set the owner for this to work.
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
If you want it to be centered horizontally, but not vertically (i.e. fixed vertical location), you will have to do that in an EventHandler after the AboutBox has been loaded because you will need to calculate the horizontal position depending on the Width of the AboutBox, and this is only known after it has been loaded.
protected override void OnInitialized(...)
{
this.Left = this.Owner.Left + (this.Owner.Width - this.ActualWidth) / 2;
this.Top = this.Owner.Top + 20;
}
gehho.
I would go the manual way, instead of count on WPF to make the calculation for me..
System.Windows.Point positionFromScreen = this.ABC.PointToScreen(new System.Windows.Point(0, 0));
PresentationSource source = PresentationSource.FromVisual(this);
System.Windows.Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(positionFromScreen);
AboutBox.Top = targetPoints.Y - this.ABC.ActualHeight + 15;
AboutBox.Left = targetPoints.X - 55;
Where ABC is some UIElement within the parent window (could be Owner if you like..) , And could also be the window itself (top left point)..
Good luck

Resources