Reputation: 520
Losing my mind here. I spent the last couple days writing the beginnings of a windows app in WinForms... yesterday did a 90 degree turn and had to switch over to WPF for aesthetic reasons. Been having some trouble converting certain things over... namely anything graphics related. In the wpf version, I had the following C# code to created a black circle and white rectangle at the point where the user clicked on the panel and display a message box displaying what the x coordinate is:
Graphics g;
private void panel1_MouseClick(object sender, MouseEventArgs e)
{
SolidBrush s2 = new SolidBrush(Color.Black);
g.FillRectangle(s2, e.X + 3, e.Y + 3, 10, 10);
SolidBrush s = new SolidBrush(Color.White);
g.FillPie(s, e.X + 4, e.Y + 4, 7, 7, 0, 360);
float x_cord = e.X;
MessageBox.Show("X is: " + x_cord.ToString());
}
I tried to do this in wfb via the following code:
Graphics g;
private void Canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
System.Windows.Point position = e.GetPosition(this);
double pX = position.X;
double pXint = Convert.ToInt32(pX);
MessageBox.Show(pX.ToString());
SolidBrush s2 = new SolidBrush(System.Drawing.Color.Black);
g.FillRectangle(s2, pXint, 5, 10, 10);
}
This compiles and runs correctly but when I click on canvas, nothing happens! The messagebox was there mainly as a test to see if the event was triggering at all, which it clearly isn't. Here's the corresponding XML for the window with the canvas in it:
<Grid>
<Canvas Name="Surface" Height="Auto" Width="Auto" Background="White"> </Canvas>
</Grid>
What am I doing wrong here? I actually like WPF better for the most part but certain things are an absolute nuisance.
Upvotes: 0
Views: 7716
Reputation: 520
Got it. Can't believe it took me 6 hours to draw a Rectangle. Not exactly sure what made it work but think it had to do somewhat with getting rid of using System.Drawing;
When I tried sa_ddam213's code I got an error saying "Cannot convert from System.Drawing.Rectangle to System.Windows.UIElement" for unknown reasons. After google search number 5007 I came upon this article:
http://msdn.microsoft.com/en-us/library/ms747393.aspx
I had looked at it before but couldn't get the code to compile for the line or the elipse, I'm thinking it was System.Drawing assembly causing problems.
Thanks so much for the help all!!
Upvotes: 1
Reputation: 43634
The problem is you are trying to Draw System.Drawing
objects onto a WPF Canvas
, you cant do that.
One way to solve this is to just add Rectangles
to you Canvas
.
<Grid>
<Canvas Name="Surface" Height="Auto" Width="Auto" Background="White" MouseLeftButtonDown="Surface_MouseLeftButtonDown"></Canvas>
</Grid>
private void Surface_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
Rectangle rect = new Rectangle { Width = 10, Height = 10, Fill = Brushes.Black };
Surface.Children.Add(rect);
Canvas.SetLeft(rect, e.GetPosition(this).X);
Canvas.SetTop(rect, e.GetPosition(this).Y);
}
Upvotes: 3