WPF Notes

WPF Notes

Notes on some WPF related things it took me a while to figure out how to do.

Setting the source of a WPF image to an embedded resource.

  Image titleImage = new titleImage(); // could also be XAML element
  System.IO.Stream file = 
    Assembly.GetExecutingAssembly().GetManifestResourceStream(
    "AssemblyName.folderIfExists.ImageName.Extension");
  BitmapFrame fr = BitmapFrame.Create(file);
  titleImage.Source = fr;

Changing the opacity using an ImageBrush when drawing on a DrawingContext

  DrawingBrush db = new DrawingBrush();
  db.AlignmentX = AlignmentX.Left;
  db.AlignmentY = AlignmentY.Top;
  db.Stretch = Stretch.None;

  DrawingVisual dv = new DrawingVisual();
  DrawingContext dc2 = dv.RenderOpen();
  dc2.DrawRectangle( new SolidColorBrush(Color.FromArgb(30,0,0,0)), null, new Rect(0,0,50,100));
  dc2.DrawRectangle( new SolidColorBrush(Color.FromArgb(200,0,0,0)), null, new Rect(50,0,100,100));
  dc2.Close();

  RenderTargetBitmap renderBitmap = new RenderTargetBitmap(100, 100, 96, 96, PixelFormats.Default);
  renderBitmap.Render(dv);

  ImageDrawing id = new ImageDrawing(renderBitmap, new Rect(0, 0, 100, 100));

  db.Drawing = id;

  dc.PushOpacityMask(db);
  dc.DrawRectangle(Brushes.Green, null, new Rect(20, 20, 100, 100));
  dc.Pop();

Rendering to a DrawingVisual in a background thread.

	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class Window1 : System.Windows.Window
	{
		public delegate void myDelegate();

		public void CreateDrawing()
		{
			DrawingVisual dv = new DrawingVisual();
			DrawingContext dc = dv.RenderOpen();
			dc.DrawLine(new Pen(Brushes.Black, 2.0), new Point(2, 2), new Point(200, 200));
			dc.Close();
			di = new DrawingImage(dv.Drawing);
			di.Freeze();
			Thread.Sleep(2000);
		}

		private DrawingImage di;

		public void CreateDrawingCompleted( IAsyncResult res )
		{
			this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, new myDelegate(DrawingToUI));
		}

		public void DrawingToUI()
		{
			myImage.Source = di;
		}

		public Window1()
		{
			InitializeComponent();

			myDelegate d = new myDelegate(CreateDrawing);
			d.BeginInvoke(CreateDrawingCompleted, null);
		}
	}