Tech Off Post

Single Post Permalink

View Thread: I always get a black backgraound with DrawingContext in WPF
  • User profile image
    Dioniz

    I am newbie to wpf and to this sort of programming in general. I have an example from Sams' WPF 4 Unleashed to which I am unable to set the background. I show it here greatly simplified and in VB.NET:

    Imports System.Windows
    Imports System.Windows.Media
    Imports System.Windows.Input
    
    Namespace WTH
       Class Application
          <STAThread()> _
          Public Shared Sub Main()
             Dim whv As New WTH.WindowHostingVisual
             whv.ShowDialog()
          End Sub
       End Class
    
       Public Class WindowHostingVisual
          Inherits Window
    
          Private visuals As New List(Of Visual)()
    
          Public Sub New()
             Title = "Hosting DrawingVisuals"
             Width = 400
             Height = 400
             WindowStartupLocation = Windows.WindowStartupLocation.CenterScreen
             Background = Brushes.Aquamarine
             Dim visLine As New DrawingVisual()
             Using dc As DrawingContext = visLine.RenderOpen()
                dc.DrawLine(New Pen(Brushes.White, 5), New Point(50, 200), New Point(350, 200))
                dc.PushOpacity(0.5)
             End Using
             visuals.Add(visLine)
          End Sub
    
          Protected Overrides ReadOnly Property VisualChildrenCount() As Integer
             Get
                Return visuals.Count
             End Get
          End Property
    
          Protected Overrides Function GetVisualChild(index As Integer) As Visual
             If index < 0 OrElse index >= visuals.Count Then
                Throw New ArgumentOutOfRangeException("index")
             End If
             Return visuals(index)
          End Function
    
       End Class
    End Namespace

    Using XAML is what I want to avoid. Otherwise, what's the point of programming if I can't change things when and as I want. When I use the standard files created Automatically by VS 2010 Express for WPF, I can change the background just fine through the Window or the Grid. Here is the empty XAML version I am using now:

    <Application x:Class="Application"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
        <Application.Resources>
            
        </Application.Resources>
    </Application>

    When I comment out the two overrides in my code, the background changes, but nothing is drawn.

    I have tried everything, so please save me from suicide.