I want the user to enter the width and height of the rectangle and I want the rectangle to appear immediately after numbers have been entered. I don't want to have to push any buttons to have the rectangle appear.
I had the rectangle code working when I entered numbers for the height and width but when I changed it to variables from the user input textbox, nothing appears on the screen.
Here's my XAML:
TextBox Text="{Binding xcoord, Mode=OneWay}" Name="x" Grid.Row="1" Height="20" Width="40" Grid.Column="2"></TextBox>
TextBox Text="{Binding ycoord, Mode=OneWay}" Name="y" Grid.Row="2" Height="20" Width="40" Grid.Column="2"></TextBox
Here's my C#:
public FEModel()
{
InitializeComponent();
CreateARectangle();
}
private double xval;
public double xcoord
{
get { return xval; }
}
private double yval;
public double ycoord
{
get { return yval; }
}
public void CreateARectangle()
{
// Creates a Rectangle
Rectangle rect = new Rectangle();
rect.Height = ycoord;
rect.Width = xcoord;
// Create a Brush
SolidColorBrush colorbrush= new SolidColorBrush();
colorbrush.Color = Colors.Red;
colorbrush.Opacity = .3;
SolidColorBrush blackBrush = new SolidColorBrush();
blackBrush.Color = Colors.Black;
// Set Rectangle's width and color
rect.StrokeThickness = 1;
rect.Stroke = blackBrush;
// Fill rectangle with color
rect.Fill =colorbrush;
// Add Rectangle to the Grid.
can.Children.Add(rect);
}
I expect the rectangle to appear on the canvas as soon as the user enters x and y coordinates but instead, nothing happens.
You need to use two way binding for your text boxes.
Here is a fully working sample.
Window Xaml: Note that the default update trigger for textbox is 'LostFocus'. In my example i set to 'PropertyChanged' so the rectangle updates as soon as the user changes a value.
<Window x:Class="WpfApp9.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp9"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Name="can">
<TextBox Text="{Binding xcoord, UpdateSourceTrigger=PropertyChanged}" Name="x" Height="20" Width="40" Margin="40,51,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Text="{Binding ycoord, UpdateSourceTrigger=PropertyChanged}" Name="y" Height="20" Width="40" Margin="40,81,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
</Grid>
</Window>
Here is the code behind. I changed the code to adjust the rectangle size rather than creating a new rectangle every time the values are changed.
using System.Windows;
using System.Windows.Media;
using System.Windows.Shapes;
namespace WpfApp9
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = this;
}
private double xval = 50;
public double xcoord
{
get=> xval;
set
{
xval = value;
CreateARectangle();
}
}
private double yval = 50;
public double ycoord
{
get => yval;
set
{
yval = value;
CreateARectangle();
}
}
Rectangle rect = null;
public void CreateARectangle()
{
if (rect == null)
{
// Creates a Rectangle
rect = new Rectangle();
rect.Height = ycoord;
rect.Width = xcoord;
// Create a Brush
SolidColorBrush colorbrush = new SolidColorBrush();
colorbrush.Color = Colors.Red;
colorbrush.Opacity = .3;
SolidColorBrush blackBrush = new SolidColorBrush();
blackBrush.Color = Colors.Black;
// Set Rectangle's width and color
rect.StrokeThickness = 1;
rect.Stroke = blackBrush;
// Fill rectangle with color
rect.Fill = colorbrush;
// Add Rectangle to the Grid.
can.Children.Add(rect);
}
else
{
rect.Height = ycoord;
rect.Width = xcoord;
}
}
}
}
As a side note you can also create the rectangle in XAML, directly binding to the textbox values.
<TextBox Text="50" Name="x" Height="20" Width="40" Margin="10,10,0,0" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<TextBox Text="50" Name="y" Height="20" Width="40" Margin="10,35,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" RenderTransformOrigin="-0.017,-0.629"/>
<Rectangle Stroke="Black" Fill="#4CFF0000" Margin="60,5,0,0" Width="{Binding ElementName=x, Path=Text, UpdateSourceTrigger=PropertyChanged}" Height="{Binding ElementName=y, Path=Text, UpdateSourceTrigger=PropertyChanged}"/>
Related
I want to use a slider to create a simple graph containing both the value for Celsius and Fahrenheit and update as I move the slider. Now the graph for Fahrenheit is showing and updates as I move the slider but the graph for Celsius does not show. The slider has a minimum="0" and maximum="100" in XAML. Targetting WPF.
What am I doing wrong?
Edit: added XAML code + target
Edit2: placed updated code underneath original code
<Window x:Class="O6._4.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:O6._4"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Calculate" HorizontalAlignment="Left" Margin="30,75,0,0" VerticalAlignment="Top" Width="75" Name="CalculateButton" Click="CalculateButton_Click" HorizontalContentAlignment="Center"/>
<Button Content="Clear" HorizontalAlignment="Left" Margin="30,105,0,0" VerticalAlignment="Top" Width="75" Name="ClearButton" Click="ClearButton_Click" HorizontalContentAlignment="Center"/>
<Label Content="xxx" HorizontalAlignment="Left" Margin="130,32,0,0" VerticalAlignment="Top" Name="fahrenheitLabel"/>
<TextBlock HorizontalAlignment="Left" Margin="130,10,0,0" TextWrapping="Wrap" Text="° Fahrenheit" VerticalAlignment="Top"/>
<Slider HorizontalAlignment="Left" Margin="30,145,0,0" VerticalAlignment="Top" Width="127" Name="celsiusSlider" ValueChanged="celsiusSlider_ValueChanged" Minimum="0" Maximum="100"/>
<Label Content="xxx" HorizontalAlignment="Left" Margin="30,168,0,0" VerticalAlignment="Top" Name="celsiusLabel"/>
<Canvas HorizontalAlignment="Left" Height="250" Margin="220,40,0,0" VerticalAlignment="Top" Width="250" Name="paperCanvas" Background="LightGray"/>
<TextBlock HorizontalAlignment="Left" Margin="250,10,0,0" TextWrapping="Wrap" Text="°C" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="315,10,0,0" TextWrapping="Wrap" Text="°F" VerticalAlignment="Top"/>
</Grid>
{
public partial class MainWindow : Window
{
private int celsius;
private int fahrenheit;
private SolidColorBrush brush;
private Rectangle rectangle;
public MainWindow()
{
InitializeComponent();
celsiusLabel.Content = Convert.ToString(celsiusSlider.Value);
fahrenheitLabel.Content = Convert.ToString(32);
brush = new SolidColorBrush(Colors.Blue);
CreateRectangle(paperCanvas, brush, celsius, 20);
CreateRectangle(paperCanvas, brush, fahrenheit, 80);
}
private void CalculateButton_Click(object sender, RoutedEventArgs e)
{
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
}
private void celsiusSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
celsius = Convert.ToInt32(celsiusSlider.Value);
celsiusLabel.Content = Convert.ToString(celsius);
fahrenheit = celsius * 9 / 5 + 32;
fahrenheitLabel.Content = Convert.ToString(fahrenheit);
//UpdateRectangle(celsiusSlider.Value);
UpdateRectangle(celsius);
UpdateRectangle(fahrenheit);
}
private void CreateRectangle(Canvas drawingArea, SolidColorBrush brush, int temperatureValue, int xPosition)
{
rectangle = new Rectangle
{
Width = 40,
Height = temperatureValue,
Margin = new Thickness(xPosition,0,0,0),
Stroke = brush,
Fill = brush,
};
drawingArea.Children.Add(rectangle);
}
private void UpdateRectangle(double sliderValue)
{
rectangle.Height = sliderValue;
}
}
Updated code
public partial class MainWindow : Window
{
private int celsius;
private int fahrenheit;
private SolidColorBrush brush;
private Rectangle celsiusRectangle;
private Rectangle fahrenheitRectangle;
public MainWindow()
{
InitializeComponent();
celsiusLabel.Content = Convert.ToString(celsiusSlider.Value);
fahrenheitLabel.Content = Convert.ToString(32);
brush = new SolidColorBrush(Colors.Blue);
celsiusRectangle = CreateRectangle(paperCanvas, brush, celsius, 20);
fahrenheitRectangle = CreateRectangle(paperCanvas, brush, fahrenheit, 80);
}
private void CalculateButton_Click(object sender, RoutedEventArgs e)
{
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
}
private void celsiusSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
celsius = Convert.ToInt32(celsiusSlider.Value);
celsiusLabel.Content = Convert.ToString(celsius);
fahrenheit = celsius * 9 / 5 + 32;
fahrenheitLabel.Content = Convert.ToString(fahrenheit);
UpdateRectangle();
}
private Rectangle CreateRectangle(Canvas drawingArea, SolidColorBrush brush, int temperatureValue, int xPosition)
{
var rectangle = new Rectangle
{
Width = 40,
Height = temperatureValue,
Margin = new Thickness(xPosition,0,0,0),
Stroke = brush,
Fill = brush,
};
drawingArea.Children.Add(rectangle);
return rectangle;
}
private void UpdateRectangle()
{
celsiusRectangle.Height = celsius;
fahrenheitRectangle.Height = fahrenheit;
}
}
}
CreateRectangle function has issue. Because you only have one private Rectangle rectangle variable. Last call CreateRectangle override celsus rectangle and lost handler. Then only fahrenheit rectangle work.
Use 2 Rectangle variable and change CreateRectangle function
private Rectangle CreateRectangle(Canvas drawingArea, SolidColorBrush brush, int temperatureValue, int xPosition)
{
var rectangle = new Rectangle //<-- Made change here
{
Width = 40,
Height = temperatureValue,
Margin = new Thickness(xPosition,0,0,0),
Stroke = brush,
Fill = brush,
};
drawingArea.Children.Add(rectangle);
return rectangle; //<-- Made change here
}
then create using like this
celsuiusRectangle= CreateRectangle(paperCanvas, brush, celsius, 20);
fahrenheitRectangle= CreateRectangle(paperCanvas, brush, fahrenheit, 80);
I have a WPF Canvas with a TextBlock and an Image on it. The text is animated, but it doesn't look smooth. I tried many combinations of different FPS-Settings and durations but it won't get better.
I also want to let the text fade-in/out at the start and ending. But I found no methods to do so.
At the moment it looks like that:
How can I get the animation smoothly? How can I fade it in/out smoothly?
Before you ask, I need to show the Window invisible because I use the WpfAppBar and that component needs an HWND.
Here is the canvas xaml:
<Canvas x:Name="canMain" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<Border x:Name="boLogo" Panel.ZIndex="2" Height="40" Background="Gray" Canvas.Left="0" Canvas.Top="-20">
<Image Height="39" Width="auto" Margin="5, 0, 5, 0" Source="pack://siteoforigin:,,,/Resources/Logo.png" />
</Border>
<TextBlock x:Name="tbInfo" Panel.ZIndex="1" Visibility="Hidden" RenderOptions.BitmapScalingMode="NearestNeighbor" FontSize="32" TextOptions.TextFormattingMode="Display" TextOptions.TextRenderingMode="ClearType" FontFamily="Arial" FontWeight="Bold" Padding="5" HorizontalAlignment="Stretch" VerticalAlignment="Center">
<TextBlock.RenderTransform>
<TranslateTransform x:Name="AnimatedTranslateTransform" X="0" Y="0" />
</TextBlock.RenderTransform>
</TextBlock>
</Canvas>
And the code to animate the text:
public void ShowWindow(Brush fontColor, Brush backgroundColor, string str) {
var helper = new WindowInteropHelper(this);
helper.EnsureHandle();
tbInfo.Foreground = fontColor;
this.Background = backgroundColor;
tbInfo.Text = str;
this.Height = 39;
this.Width = SystemParameters.WorkArea.Width;
this.Left = SystemParameters.PrimaryScreenWidth - this.Width;
ShowWindowInvisible();
WpfAppBar.AppBarFunctions.SetAppBar(this, WpfAppBar.ABEdge.Top);
Visibility = Visibility.Visible;
int duration = 10 + str.Length / 5;
TextMarquee(duration);
}
private void TextMarquee(int duration)
{
Timeline.DesiredFrameRateProperty.OverrideMetadata(
typeof(Timeline),
new FrameworkPropertyMetadata { DefaultValue = 60 }
);
double height = canMain.ActualHeight - tbInfo.ActualHeight;
tbInfo.Margin = new Thickness(0, height / 2, 0, 0);
DoubleAnimation doubleAnimation = new DoubleAnimation();
doubleAnimation.From = canMain.ActualWidth;
doubleAnimation.To = tbInfo.ActualWidth *-1;
doubleAnimation.RepeatBehavior = RepeatBehavior.Forever;
doubleAnimation.Duration = new Duration(TimeSpan.FromSeconds(duration));
tbInfo.BeginAnimation(Canvas.LeftProperty, doubleAnimation);
tbInfo.Visibility = Visibility.Visible;
}
private void ShowWindowInvisible()
{
var width = Width;
var height = Height;
var windowStyle = WindowStyle;
var showInTaskbar = ShowInTaskbar;
var showActivated = ShowActivated;
Width = 0;
Height = 0;
WindowStyle = WindowStyle.None;
ShowInTaskbar = false;
ShowActivated = false;
Show();
Visibility = Visibility.Hidden;
Width = width;
Height = height;
WindowStyle = windowStyle;
ShowInTaskbar = showInTaskbar;
ShowActivated = showActivated;
}
I have a WPF app that I'm testing which loads a XML and visualizes it in a usercontrol. Now the issue I'm having is that every time I load my user control the HorizontalAlignment is okay, but the VerticalAlignment doesn't adept to the height size of the usercontrol.
Anyone has an idea how to solve this?
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:UserControls="clr-namespace:RackBuildingTesT.UserControls" x:Class="RackBuildingTesT.MainWindow"
Title="MainWindow" Height="578" Width="758" SizeChanged="Window_SizeChanged_1">
<Grid>
<DockPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Border DockPanel.Dock="Top" BorderBrush="Black" BorderThickness="1">
<Grid>
<Label Content="Welke rack laden" HorizontalAlignment="Left" VerticalAlignment="Top"/>
<ComboBox x:Name="RackChooser" HorizontalAlignment="Left" Margin="100,0,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="RackChooser_SelectionChanged"/>
</Grid>
</Border>
<Border DockPanel.Dock="Top" BorderBrush="Black" BorderThickness="1">
<Grid x:Name="RackGrid" Margin="0,0,0,0">
</Grid>
</Border>
</DockPanel>
</Grid>
MainWindow.xaml.cs
public MainWindow()
{
InitializeComponent();
LoadRackCombo();
}
private void LoadRackCombo()
{
var files = Directory.GetFiles(Properties.Settings.Default.FilePathXMLRack);
foreach (var item in files)
{
RackChooser.Items.Add(item);
}
}
private void RackChooser_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
this.RackGrid.Children.Clear();
this.Cursor = Cursors.Wait;
if (RackChooser.SelectedIndex == -1)
MessageBox.Show("Select a rack");
else
{
string rackFile = Convert.ToString(RackChooser.Items[RackChooser.SelectedIndex]);
UserControls.RackBuilder r = new UserControls.RackBuilder();
RackGrid.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
RackGrid.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
r.Width = RackGrid.Width;
r.Height = RackGrid.Height;
var _r = TRack.CreateFromXMLFile(rackFile, null);
r.set_Rack(_r);
RackGrid.Children.Add(r);
}
this.Cursor = Cursors.Arrow;
}
private void Window_SizeChanged_1(object sender, SizeChangedEventArgs e)
{
RackGrid.Width = this.Width;
RackGrid.Height = this.Height;
}
RackBuilder.xaml.cs (xaml page is standard WPF usercontrol)
public RackBuilder()
{
InitializeComponent();
}
public TRack fRack { get; set; }
public void set_Rack(TRack value)
{
this.fRack = value;
this.InvalidateVisual();
}
protected override void OnRender(DrawingContext drawingContext)
{
if (this.fRack != null)
{
var xScale = this.Width / this.fRack.Size.Width;
var yScale = this.Height / this.fRack.Size.Height;
var smallest = 0.0;
if (xScale < yScale)
smallest = xScale;
else
smallest = yScale;
foreach (var hole in this.fRack.HolePositions)
{
drawingContext.DrawEllipse(Brushes.Aquamarine, null, new Point(hole.Position.X * xScale, hole.Position.Y * yScale),
hole.Diameter * smallest * 0.5, hole.Diameter * smallest * 0.5);
}
}
}
Result
Instead of adding your Control to a Grid, use the ContentControl and add it to its Content-Property.
It also stretches its child automatically.
I fixed it with putting the MainWindow SizeToContent to WidthAndHeight.
I am building an image viewer.
I have created a functionality that when the user moves the slider, it changes the ZoomLevel property value. This subsequently zooms the image based on the value provided by the ZoomLevel property.
<Image
Name="image"
Source="Sample1.jpg"
Opacity="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Stretch="None"
RenderTransformOrigin="0.5,0.5"
RenderOptions.BitmapScalingMode="HighQuality">
<Image.RenderTransform>
<TransformGroup>
<ScaleTransform
ScaleX="{Binding Path=ZoomLevel}"
ScaleY="{Binding Path=ZoomLevel}" />
<TranslateTransform />
</TransformGroup>
</Image.RenderTransform>
</Image>
I wish to be able to animate the zooming with a DoubleAnimation. Animation is supposed to start from the current zoom level and then get to the zoom specified in the bound ZoomLevel property. It would be great if someone could provide some help in XAML. Thanks!
Mouse wheel code:
private void border_MouseWheel(object sender, MouseWheelEventArgs e)
{
int delta;
delta = e.Delta;
zoom(delta);
}
private void zoom(int delta)
{
double zoomIncrement;
//Different zoom levels at different zoom stages
if (ZoomLevel > 2)
{
zoomIncrement = Math.Sign(delta) * 0.2;
}
else if (ZoomLevel >= 1 && ZoomLevel <= 2)
{
zoomIncrement = Math.Sign(delta) * 0.1;
}
else
{
zoomIncrement = Math.Sign(delta) * 0.06;
}
//Rounding zoom level to boundary values
//Zooming is allowed from 10% to 600%
if (ZoomLevel + zoomIncrement > 6)
{
ZoomLevel = 6;
}
else if (ZoomLevel + zoomIncrement < 0.1)
{
ZoomLevel = 0.1;
}
else
{
ZoomLevel += zoomIncrement;
}
}
It is a little messy but try this.
namespace Zoom
{
public partial class Window1
{
public double ZoomLevel { get; set; }
public double SlideLevel { get; set; }
public Window1()
{
InitializeComponent();
ZoomLevel = 1.0;
SlideLevel = 1.0;
image.MouseWheel += image_MouseWheel;
}
private void image_MouseWheel(object sender, MouseWheelEventArgs e)
{
double zoom = e.Delta > 0 ? .1 : -.1;
slider.Value = (SlideLevel + zoom);
}
private void ZoomImage(double zoom)
{
Storyboard storyboardh = new Storyboard();
Storyboard storyboardv = new Storyboard();
ScaleTransform scale = new ScaleTransform(ZoomLevel, ZoomLevel);
image.RenderTransformOrigin = new Point(0.5, 0.5);
image.RenderTransform = scale;
double startNum = ZoomLevel;
double endNum = (ZoomLevel += zoom);
if (endNum > 1.0)
{
endNum = 1.0;
ZoomLevel = 1.0;
}
DoubleAnimation growAnimation = new DoubleAnimation();
growAnimation.Duration = TimeSpan.FromMilliseconds(300);
growAnimation.From = startNum;
growAnimation.To = endNum;
storyboardh.Children.Add(growAnimation);
storyboardv.Children.Add(growAnimation);
Storyboard.SetTargetProperty(growAnimation, new PropertyPath("RenderTransform.ScaleX"));
Storyboard.SetTarget(growAnimation, image);
storyboardh.Begin();
Storyboard.SetTargetProperty(growAnimation, new PropertyPath("RenderTransform.ScaleY"));
Storyboard.SetTarget(growAnimation, image);
storyboardv.Begin();
}
private void slider_ValueChanged(object sender, System.Windows.RoutedPropertyChangedEventArgs<double> e)
{
double zoomChange = (SlideLevel - slider.Value) * -1;
SlideLevel = SlideLevel + zoomChange;
ZoomImage(zoomChange);
}
}
}
I found this other stack question to be quite helpful
Here is the current setup of XAML that I have as well.
<Border MaxWidth="500"
MaxHeight="500"
Height="500"
Width="500"
Name="border">
<Image
Name="image"
Source="picture1.png"
Opacity="1"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Stretch="Fill"
RenderTransformOrigin="0.5,0.5"
RenderOptions.BitmapScalingMode="HighQuality"
ClipToBounds="True">
</Image>
</Border>
<Slider
HorizontalAlignment="Left"
Margin="44,70,0,148"
Name="slider"
Width="24"
Value="1.0"
Minimum="0"
Maximum="1.0"
LargeChange="0.1"
Orientation="Vertical"
FlowDirection="LeftToRight"
TickFrequency="0.1"
IsSnapToTickEnabled="False"
ValueChanged="slider_ValueChanged" />
Have you tried using a ViewBox? You can bind the final width to any value you need, here's a quick sample:
<Window.Resources>
<Storyboard x:Key="ZoomIn">
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(FrameworkElement.Width)" Storyboard.TargetName="ImageContainer">
<EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="400"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</Window.Resources>
<Grid x:Name="LayoutRoot">
<Viewbox x:Name="ImageContainer" Width="200">
<Image Source="http://images.wikia.com/lossimpson/es/images/a/a7/Homer_Simpson2.png"/>
</Viewbox>
</Grid>
I am trying to create Rectangle programmaticallyin silverlight as fallows.
C#
private Boolean Working = false;
const int scale = 4;
const int size = 50;
Int32[] data = new Int32[size];
Rectangle[] lines = new Rectangle[size];
private void button1_Click(object sender, RoutedEventArgs e)
{
canvas1.Children.Clear();
for (int i = 0; i < data.Length; i++)
{
data[i] = i;
lines[i] = new Rectangle()
{
Height=i*scale,
Width = 10,
StrokeThickness=5,
Stroke = new SolidColorBrush(Colors.Red),
Name=i.ToString(),
};
canvas1.Children.Add(lines[i]);
}
}
Now the problem is that all the rectangle are created with the same height and width?.
XAML
<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="500" d:DesignWidth="500">
<Canvas x:Name="canvas2" Background="White">
<Canvas x:Name="canvas1" Background="White"></Canvas>
<Button Content=" Generate" Height="38" Name="button1" Width="75" Click="button1_Click" Margin="0,352,245,24" HorizontalAlignment="Right" Canvas.Left="12" Canvas.Top="85" />
<Button Content="Shuffle" Height="38" HorizontalAlignment="Left" Name="button2" Margin="12,352,0,24" Click="button2_Click_1" Canvas.Left="81" Canvas.Top="85" Width="71" />
<Button Canvas.Left="181" Canvas.Top="437" Content="Bubble Sort" Height="38" Name="button3" Width="109" Click="button3_Click" />
</Canvas>
</UserControl>
Screenshot
Actually, everything works fine. All rectangles have different height. But you forget to move them, so they start overlapping. Change a little code and you'll see:
lines[i] = new Rectangle()
{
Height = i * scale,
Width = 10,
StrokeThickness = 5,
Stroke = new SolidColorBrush(Colors.Red),
Name = i.ToString(),
};
lines[i].Margin = new Thickness(11 * i, 0, 0, 0);
Result