Putting WPF Control (ComboBox) on the canvas using Visuals

I am writing a WPF diagram and use Visuals for performance. The code looks like this:

public class DrawingCanvas2 : Canvas { private List<Visual> _visuals = new List<Visual>(); protected override Visual GetVisualChild( int index ) { return _visuals[index]; } protected override int VisualChildrenCount { get { return _visuals.Count; } } public void AddVisual( Visual visual ) { _visuals.Add( visual ); base.AddVisualChild( visual ); base.AddLogicalChild( visual ); } } 

Next to DrawingVisual elements (line, text) I need a ComboBox in a chart. So I tried this:

  public DrawingCanvas2() { ComboBox box = new ComboBox(); AddVisual( box ); box.Width = 100; box.Height = 30; Canvas.SetLeft( box, 10 ); Canvas.SetTop( box, 10 ); } 

but it does not work, ComboBox is not displayed. What am I missing?

+4
source share
3 answers

Correct answer: Linda Liu, Microsoft WPF forum , although XIU came close to it.

the code:

  public DrawingCanvas2() : base() { ComboBox box = new ComboBox(); AddVisual( box ); Size outputSize = new Size( 100, 20 ); box.Measure( outputSize ); box.Arrange( new Rect( outputSize ) ); box.UpdateLayout(); box.Items.Add( "hello1" ); box.Items.Add( "hello2" ); box.Items.Add( "hello3" ); box.SelectedIndex = 1; } 

It is important to note that box.SelectedIndex must not be explicitly set to -1 , otherwise the elements in the field are not selected.

0
source

Have you just considered placing a ComboBox inside a container panel along with DrawingCanvas2 and on top of DrawingCanvas2 in terms of z-order?

That way, your DrawingCanvas2 can focus on drawing Visuals, and your ComboBox will behave out of the box.

+1
source

Canvas will "get" its size from the Children property (using MeasureOverride and ArrangeOverride). Since you just call AddVisualChild, it is not added to the Children property, and it still considers it to be empty.

The Children property is a UIElementCollection (ComboBox - UIElement)

+1
source

Source: https://habr.com/ru/post/1303512/


All Articles