using System; using System.Collections.Generic; using System.Text; 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; using System.Collections; using System.Windows.Media.Effects; namespace CanvasControl { /// /// Interaction logic for Window1.xaml /// public partial class Window1 : System.Windows.Window { public Window1() { InitializeComponent(); Resources.Source = new Uri("pack://application:,,,/CanvasControl;component/ResourceSet.xaml"); Content = MakeCanvas(); Background = Brushes.Black; SizeToContent = SizeToContent.WidthAndHeight; } private Canvas MakeCanvas() { Canvas c=new Canvas(); //You can extract the bounds of the individual elements, or operate with a fixed size here c.Width = 443; c.Height = 355; foreach (DictionaryEntry de in Resources) { DrawingBrush db = (de.Value as DrawingBrush); if (db != null) { DrawingGroup dg = (db.Drawing as DrawingGroup); if (dg != null) { GeometryDrawing gd = (dg.Children[0] as GeometryDrawing); if (gd != null) { Path path = new Path(); path.Name = (string)de.Key; //Directly assign the pertinent properties of interest path.Data = gd.Geometry; path.Stroke = gd.Pen.Brush; path.StrokeThickness = gd.Pen.Thickness; path.Fill = gd.Brush; //On these Events we can modify our sweet vector content path.MouseEnter += new MouseEventHandler(path_MouseEnter); path.MouseLeave += new MouseEventHandler(path_MouseLeave); c.Children.Add(path); c.Children.Add(CreateNameBlock(gd,path.Name)); } } } } return c; } void path_MouseLeave(object sender, MouseEventArgs e) { Path p = sender as Path; p.BitmapEffect = null; } void path_MouseEnter(object sender, MouseEventArgs e) { Path p = sender as Path; p.BitmapEffect = new EmbossBitmapEffect(); } private TextBlock CreateNameBlock(GeometryDrawing drawing, string name) { TextBlock tb = new TextBlock(); tb.Text = name; tb.Background = Brushes.Transparent; tb.Foreground = Brushes.Black; //Make invisible to hittesting to allow the paths to receieve hit test events tb.IsHitTestVisible = false; //Canvas does not provide layout services - //We need to measure the size of the textbox in order to align it horizontally and vertically ourselves tb.Measure(new Size(double.MaxValue, double.MaxValue)); Size s = tb.DesiredSize; //The geometry bounds are available Rect bounds = drawing.Bounds; double posX = bounds.Left + bounds.Size.Width / 2 - s.Width / 2; double posY = bounds.Top + bounds.Size.Height / 2 - s.Height / 2; Canvas.SetLeft(tb, posX); Canvas.SetTop(tb, posY); return tb; } } }