Add rectangle controls dynamically to silverlight - c#

In the following code snippet I am adding new rectangle on button click.
Currently they are adding from top to bottom but I want to add them in bottom to top order
<UserControl x:Class="StackImp.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="300" d:DesignWidth="400">
<Canvas x:Name="LayoutRoot" Background="White">
<Canvas x:Name="canvasChild" Background="Red"></Canvas>
<Button x:Name="btnPush" Content="Add" Height="20" Width="40" Margin="12,268,348,12" Click="btnPush_Click"></Button>
<Button Content="Remove" Height="20" Margin="78,268,282,12" Name="btnPop" Width="40" />
</Canvas>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace StackImp
{
public partial class MainPage : UserControl
{
StackPanel sp1 = new StackPanel();
public MainPage()
{
InitializeComponent();
sp1.Orientation = Orientation.Vertical;
canvasChild.Children.Add(sp1);
}
private void btnPush_Click(object sender, RoutedEventArgs e)
{
Rectangle rect = new Rectangle()
{
Height = 30,
Width = 30,
StrokeThickness = 3,
Stroke = new SolidColorBrush(Colors.Red),
};
sp1.Children.Add(rect);
}
}
}

Try this one.
XAML
<Grid x:Name="LayoutRoot" Background="White">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Content="Add Rectangle" Click="Button_Click" />
<StackPanel x:Name="sp1" Grid.Row="1" VerticalAlignment="Bottom"/>
</Grid>
C#
private void Button_Click(object sender, RoutedEventArgs e)
{
Border border = new Border();
border.Height = 50;
border.Width = 50;
border.BorderBrush = new SolidColorBrush(Colors.Black);
border.BorderThickness = new Thickness(2);
border.Child = new TextBlock()
{
Text = sp1.Children.Count.ToString(),
HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
VerticalAlignment = System.Windows.VerticalAlignment.Center
};
sp1.Children.Insert(0, border);
}

I think rect.VerticalAlignment = VerticalAlignment.Bottom and sp1.Children.Insert(0, rect) will help you.

Related

Refreshing canvas

I have a question about refreshing canvas. There is .Refresh() or .Clear() in WinForms.But what about WPF?
I watched some methods how to do it, but it didn't help me at all.
The situation is that my canvas contains textBox and Button. When I click button I can draw some ellipses.
And I need to clear these ellipses after my every click on button but without clearing textBox and Button from this Canvas!
My WPF Xaml:
<Window x:Class="draw.CreateEllipse"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Create" Height="768" Width="1024" WindowStartupLocation="CenterScreen" Name="Create" Closed="Create_Closed">
<Canvas Name="can" Background="White" MouseDown="can_MouseDown">
<TextBox Name="txbNumber" Height="34" Canvas.Left="797" TextWrapping="Wrap" Text="5" Canvas.Top="76" Width="209" FontSize="18"/>
<Button Name="btnCreate" Content="Create" Canvas.Left="797" Canvas.Top="130" Width="209" Height="66" FontSize="18" Click="btnCreate_Click"/>
</Canvas>
My C# :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace draw
{
/// <summary>
/// Логика взаимодействия для CreateGraph.xaml
/// </summary>
public partial class Create : Window
{
public Create()
{
InitializeComponent();
}
int n, i;
Ellipse[] v;
Rectangle rect = new Rectangle();
SolidColorBrush solidcolor = new SolidColorBrush();
private void btnCreate_Click(object sender, RoutedEventArgs e)
{
n = Convert.ToInt16(txbNumber.Text);
v = new Ellipse[n];
//can.Children.Clear();
}
private void Create_Closed(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void can_MouseDown(object sender, MouseButtonEventArgs e)
{
solidcolor.Color = Colors.Transparent;
//Ellipse myEllipse = new Ellipse();
SolidColorBrush mySolidColorBrush = new SolidColorBrush();
for (i = 0; i < n; i++)
{
v[i] = new Ellipse();
mySolidColorBrush.Color = Colors.Transparent;
v[i].Fill = mySolidColorBrush;
v[i].StrokeThickness = 2;
v[i].Stroke = Brushes.Black;
v[i].Width = 75;
v[i].Height = 75;
v[i].Margin = new Thickness(e.GetPosition(can).X, e.GetPosition(can).Y, 0, 0);
can.Children.Add(v[i]);
}
if (n <= 0)
return;
n--;
}
}
}
you can separate your elements with this code:
var can2 = can.Children.OfType<Ellipse>();
above code select all of Ellipses in your Canvas "can".
and you can remove them from your Canvas Like this:
foreach (var element in can2)
{
can.Children.Remove(element);
}
Now you have no ellipse in your Canvas.
Hope this helps you.

WPF. How to add text under image in c#

I have image which I set behind code and now I have to set 3 texts under the picture also behind code, maybe somenoe knoe how to make it?
my xaml:
...<Style x:Key="imageStyle" TargetType="{x:Type Image}">
<Setter Property="Height" Value="152px"/>
<Setter Property="Width" Value="762"/>
</Style>
</windows.Resources>
<Grid>
<StackPanel x:Name="StackStyle" Background="#FFFFFF" Margin="30,98,250,150">...
My xaml.cs is:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
Style imgStyle = (Style)Resources["imageStyle"];
var imag = new Image();
imag.Style = imgStyle;
string path = System.AppDomain.CurrentDomain.BaseDirectory + "../../ico.choose-coupon.png";
imag.Source = new BitmapImage(new Uri(path));
StackStyle.Children.Add(imag);
}
}
do not forget that this is one image, and these text have to be under Gray field.
UPDATE:
I get what I want, thats the code:
xaml:
<Viewbox Stretch="Fill">
<Grid>
<StackPanel Orientation="Vertical" x:Name="myStackPanel" Background="#FFFFFF" Height="560" Width="968" HorizontalAlignment="Center" >
<Label Style="{StaticResource Label}" ></Label>
</StackPanel>
</Grid>
</Viewbox>
xaml.cs:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
{
string path = System.AppDomain.CurrentDomain.BaseDirectory + "../../ico.choose-coupon.png";
Style imgStyle = (Style)Resources["imageStyle"];
var imag = new Image();
imag.Style = imgStyle;
imag.Source = new BitmapImage(new Uri(path));
myStackPanel.Children.Add(imag);
Style textStyle = (Style) Resources["textStyle"];
var text1 = new TextBlock();
var text2 = new TextBlock();
var text3 = new TextBlock();
text1.Style = textStyle;
text2.Style = textStyle;
text3.Style = textStyle;
text1.Text = "% coupon";
text2.Text = "Tara receipt";
text3.Text = "Value coupon";
text1.Margin = new Thickness(135,22,0,0);
text2.Margin = new Thickness(210, 22, 0, 0);
text3.Margin = new Thickness(188, 22, 0, 0);
var TextPanel = new StackPanel();
TextPanel.Orientation = Orientation.Horizontal;
TextPanel.Children.Add(text1);
TextPanel.Children.Add(text2);
TextPanel.Children.Add(text3);
myStackPanel.Children.Add(TextPanel);
}
}
You can use a button style. For the Text and the Image you can set an binding to the propertys. Maybe you write an Style for the button so that looks like in your example.
<Button>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Source}">
<Label Padding="0" Text="{Binding YourText}"></Label>
</StackPanel>
</Button>
Here is an exmaple of simple UserControl:
Add new userControl template to your project.
I am attaching an example of userControl with TextBox and TextBlock:
<UserControl
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"
x:Class="WpfApplication1.Example"
x:Name="UserControl"
d:DesignWidth="640" d:DesignHeight="480" Width="40" Height="40">
<Grid x:Name="LayoutRoot" Width="40" Height="40" Background="White">
<TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" Text="Test " VerticalAlignment="Top" Height="14.32"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="0,17,0,0" TextWrapping="Wrap" Text="Text" VerticalAlignment="Top" Width="40"/>
</Grid>
</UserControl>
Then in your window, just call to your userControl as much as you want(You can pass objects to it too):
<local:Example HorizontalAlignment="Left" Margin="16.4,22.4,0,0" VerticalAlignment="Top"/>
<local:Example HorizontalAlignment="Left" Margin="16.4,22.4,0,0" VerticalAlignment="Top"/>
<local:Example HorizontalAlignment="Left" Margin="16.4,22.4,0,0" VerticalAlignment="Top"/>

ui elements not working on windows phone 8 maps

i am trying to create a map object on windows phone 8 and nothing shows yet i have no errors on my code. help me heres the code:
the ui element doesnt show on the map and yet i created a polygon, and a rectangle element on the grid.
here is my xaml:
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:maps="clr-namespace:Microsoft.Phone.Maps.Controls;assembly=Microsoft.Phone.Maps"
x:Class="Fisheries.Landing_site"
mc:Ignorable="d"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="False">
<!--LayoutRoot contains the root grid where all other page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="Landing Sites" Style="{StaticResource PhoneTextNormalStyle}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<maps:Map x:Name="MyMap" Center="5.354683, 24.644135" ZoomLevel="10" LandmarksEnabled="True" PedestrianFeaturesEnabled="True"/>
</Grid>
</Grid>
and here is my cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Device.Location;
using Windows.Devices.Geolocation;
using Microsoft.Phone.Maps.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
namespace Fisheries
{
public partial class Landing_site : PhoneApplicationPage
{
public Landing_site()
{
InitializeComponent();
UpdateMap();
/* Rectangle MyRectangle = new Rectangle();
MyRectangle.Fill = new SolidColorBrush(Colors.Black);
MyRectangle.Height = 20;
MyRectangle.Width = 20;
MyRectangle.SetValue(Grid.RowProperty, 0);
MyRectangle.SetValue(Grid.ColumnProperty, 0);*/
}
public void UpdateMap()
{
Map drew = new Map();
drew.Margin = new Thickness(-12, 0, 0, 0);
ContentPanel.Children.Add(drew);
drew.SetView(new GeoCoordinate(5.354683, 24.644135), 3.5D);
//creating the grid
Grid MyGrid = new Grid();
MyGrid.RowDefinitions.Add(new RowDefinition());
MyGrid.RowDefinitions.Add(new RowDefinition());
MyGrid.Background = new SolidColorBrush(Colors.Transparent);
//Creating a Rectangle
Rectangle MyRectangle = new Rectangle();
MyRectangle.Fill = new SolidColorBrush(Colors.Black);
MyRectangle.Height = 20;
MyRectangle.Width = 40;
MyRectangle.SetValue(Grid.RowProperty, 0);
MyRectangle.SetValue(Grid.ColumnProperty, 0);
//adding a rectangle to the grid
MyGrid.Children.Add(MyRectangle);
//Creating a Polygon
Polygon MyPolygon = new Polygon();
MyPolygon.Points.Add(new Point(2, 0));
MyPolygon.Points.Add(new Point(22, 0));
MyPolygon.Points.Add(new Point(2, 40));
MyPolygon.Stroke = new SolidColorBrush(Colors.Black);
MyPolygon.Fill = new SolidColorBrush(Colors.Black);
MyPolygon.SetValue(Grid.RowProperty, 1);
MyPolygon.SetValue(Grid.ColumnProperty, 0);
//addding a new polygon to the grid
//Creating a MapOverlay and adding the Grid to it.
MapOverlay MyOverlay = new MapOverlay();
MyOverlay.Content = MyGrid;
MyGrid.Children.Add(MyPolygon);
//setting the geolocation cordiante to work on some polygon to show on the map
MyOverlay.GeoCoordinate = new GeoCoordinate(5.354683, 24.644135);
//this is where is set the position overlay to a specific location on the map
MyOverlay.PositionOrigin = new Point(0, 0.5);
//Creating a MapLayer and adding the MapOverlay to it
MapLayer MyLayer = new MapLayer();
MyLayer.Add(MyOverlay);
MyMap.Layers.Add(MyLayer);
}
}
}

VisualBrush from Window retains image of previous VisualBrush

Using VisualBrush, I am taking snapshots of a Window that contains a TabControl.
Snapshot #1:
Switch to "Dos" (not Microsoft), snapshot #2:
If I just take a picture of the TabControl or the DockPanel, everything works fine, this problem is particular to taking a picture of the Window. Help!!
Code behind:
using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
namespace WpfVisual
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var bitmapSource = this.TakeSnapshot(this);
Snapshot.Source = bitmapSource;
}
public BitmapSource TakeSnapshot(FrameworkElement element)
{
if (element == null)
{
return null;
}
var width = Math.Ceiling(element.ActualWidth);
var height = Math.Ceiling(element.ActualHeight);
element.Measure(new Size(width, height));
element.Arrange(new Rect(new Size(width, height)));
var visual = new DrawingVisual();
using (var dc = visual.RenderOpen())
{
var target = new VisualBrush(element);
dc.DrawRectangle(target, null, new Rect(0, 0, width, height));
dc.Close();
}
var renderTargetBitmap = new RenderTargetBitmap((int)width, (int)height, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(visual); // maybe here?
return renderTargetBitmap;
}
}
}
Xaml:
<Window x:Class="WpfVisual.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<DockPanel>
<TabControl x:Name="Tabs" DockPanel.Dock="Left" Width="200">
<TabItem Header="Uno">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
FontSize="50" Foreground="Red">#1</TextBlock>
</TabItem>
<TabItem Header="Dos">
<TextBlock HorizontalAlignment="Center" VerticalAlignment="Center"
FontSize="50" Foreground="Green">#2</TextBlock>
</TabItem>
</TabControl>
<Button DockPanel.Dock="Top" Margin="10" FontSize="14" Click="Button_Click">Take a snapshot</Button>
<Image x:Name="Snapshot" Margin="10,0,10,10"></Image>
</DockPanel>
</Window>
I found that I was able to get it to work by commenting out the part where I make a VisualBrush from the Window.
//var visual = new DrawingVisual();
//using (var dc = visual.RenderOpen())
//{
// var target = new VisualBrush(element);
// dc.DrawRectangle(target, null, new Rect(0, 0, width, height));
// dc.Close();
//}
and to call the element directly in renderTargetBitmap.Redner
renderTargetBitmap.Render(element);
though now I'm not sure why I ended up using DrawRectangle and VisualBrush when I could have just rendered the element directly.

Dynamically create Rectange in silverlight?

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

Categories