0

this is very simple example to show my question.

1

public class TestControl : UserControl
    {
        public TestControl()
        {
           
        }

        protected override void OnRender(DrawingContext context)
        {
            drawCircle(context);
            base.OnRender(context);
        }

        private void drawCircle(DrawingContext context)
        {
            context.DrawEllipse(Brushes.Red, null, new Point(50, 50), 50, 50);
        }
        public void drawRect()
        {
            DrawingContext context = new DrawingVisual().RenderOpen();
            context.DrawRectangle(Brushes.Green, null, new Rect(0, 0,200, 100));
        }
    }

2、 The Window front

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="300"/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        <Grid Background="White" x:Name="root">
            <local:TestControl x:Name="progressBar"   HorizontalContentAlignment="Stretch"/>
        </Grid>
        <Grid Grid.Row="1">
            <Button Content="Init" Click="Button_Click" Width="100" Height="40"/>
        </Grid>
        
    </Grid>

and 3、

 public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            Loaded += MainWindow_Loaded;
        }

   
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
         
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            progressBar.drawRect();

        }
    }

Question is:Red Circle in Render() showwed in windows.the green Rect never to show。 dont know why

I think when render finished,the DrawingContext disposed,how to append in the first drawingcontext

张成龙
  • 11
  • 1
  • The DrawingVisual created in the drawRect method is not part of the visual tree and hence never shown. See [Using DrawingVisual Objects](https://learn.microsoft.com/en-us/dotnet/desktop/wpf/graphics-multimedia/using-drawingvisual-objects?view=netframeworkdesktop-4.8) for further explanation. – Clemens Jul 10 '23 at 07:12
  • You should generally also call `base.OnRender(context);` as the first statement in an overridden OnRender method. Subsequent drawings will thus be put on top of the base class rendering output. Set the UserControl's Background property to see what happens. – Clemens Jul 10 '23 at 07:12

0 Answers0