12

How to set x, y coordinates of WPF canvas children through code? Below is my sample code.

Canvas root = new Canvas();
double y = 5;
for (int i=0; i< 10; i++)
{
    Ellipse e = new Ellipse();
    e.Height=10;
    e.Width=10;
    e.Stroke =Brushes.Black;

    root.Children.Add(e);
    y +=10;
}

MyRootCanvas = root;

MyRootCanvas is a property of type Canvas bound to WPF UserControl's content.

6
  • @HighCore I need to load the controls dynamically. Feb 7, 2014 at 19:23
  • 1
    Then use an ItemsControl. WPF's idea of dynamically is really different from other technologies. I strongly suggest you learn to use WPF properly, otherwise you will have all sorts of troubles due to the complexity of the Visual Tree. Feb 7, 2014 at 19:27
  • @HighCore I am using an ItemsControl. My UserControl is loaded in an ItemsControl. Feb 7, 2014 at 19:29
  • If you're using an ItemsControl then there is no need to create or manipulate UI elements in procedural code. That's what XAML is for. Use DataBinding properly. Feb 7, 2014 at 19:30
  • 1
    if you have a lot of UI elements, a proper DataBinding approach will be better because it may eventually improve performance due to the ability to use UI virtualization, whereas your current procedural code approach will not. From MSDN: The following is a list of conditions that disable UI virtualization: - Item containers are added directly to the ItemsControl. For example, if an application explicitly adds ListBoxItem objects to a ListBox, the ListBox does not virtualize the ListBoxItem objects. Feb 7, 2014 at 19:34

2 Answers 2

22

Use Canvas.SetLeft and Canvas.SetTop methods to set x, y coordinate for child:

for (int I=1; I<= 10; I++)
{
    Ellipse e = new Ellipse();
    e.Height=10;
    e.Width=10;
    e.Stroke =Brushes.Black;

    Canvas.SetLeft(e, 10); <-- HERE
    Canvas.SetTop(e, Y);

    root.Children.Add(e);
    Y +=10;
}
2
  • Are you sure of the order? Shouldn't the child be added before setting its position. Anyways, I did that and it works hence I would be marking your answer but, please correct it for other users. Feb 7, 2014 at 19:21
  • 4
    Canvas.SetLeft and Canvas.SetTop are static methods of canvas. And you can set it before actually adding item to canvas. Attached properties can always be set before adding item in parent.
    – Rohit Vats
    Feb 7, 2014 at 19:26
16

I know this question has already been answered but what HighCore is talking about (i.e. don't manipulate UI elements in code) cannot be stated strongly enough. To do this properly you should create a class to encapsulate the data you want to display:

public class Widget : ViewModelBase
{
    private double _X;
    public double X
    {
        get { return _X;}
        set { _X = value; RaisePropertyChanged(() => this.X); }
    }

    private double _Y;
    public double Y
    {
        get { return _Y;}
        set { _Y = value; RaisePropertyChanged(() => this.Y); }
    }

    private double _Width;
    public double Width
    {
        get { return _Width;}
        set { _Width = value; RaisePropertyChanged(() => this.Width); }
    }

    private double _Height;
    public double Height
    {
        get { return _Height;}
        set { _Height = value; RaisePropertyChanged(() => this.Height); }
    }

    private System.Windows.Media.Color _Color;
    public System.Windows.Media.Color Color
    {
        get { return _Color;}
        set { _Color = value; RaisePropertyChanged(() => this.Color); }
    }
}

It's a bit annoying having to create these dependency properties for each parameter, I use the built-in Code Snippets Manager to create a snippet for me so that I don't have to type in the whole thing every time. Next you want to create an array of these and put them in a view model somewhere, that's where the logic to generate your ellipses should go:

public MyViewModel()
{
    for (int y = 0; y < 10; y++)
        for (int x = 0; x < 10; x++)
            this.Items.Add(new Widget {
                X = x * 20,
                Y = y * 20,
                Width = 10,
                Height = 10,
                Color = Color.FromArgb(255, (byte)(x * 20), (byte)(y * 20), 0)
            });
}

You would then set an instance of MyViewModel as the data context for the window containing your canvas. All that remains is the XAML that loosely binds to this view model, you want to render a list of items onto a canvas so you use ItemsControl and replace the default items panel with a canvas:

<ItemsControl ItemsSource="{Binding Items}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Ellipse Width="{Binding Width}" Height="{Binding Height}">
                <Ellipse.Stroke>
                    <SolidColorBrush Color="{Binding Color}" />
                </Ellipse.Stroke>
            </Ellipse>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemContainerStyle>
        <Style>
            <Setter Property="Canvas.Left" Value="{Binding X}" />
            <Setter Property="Canvas.Top" Value="{Binding Y}" />
        </Style>
    </ItemsControl.ItemContainerStyle>
</ItemsControl>

And here's the result:

circles

You now have your front-end data-bound to your view model so you can add/remove items or change individual properties etc and the changes will propagate through. You can also unit test your logic without having to actually create the view controls at all.

5
  • 1
    I know this post is from years ago, but I just found it useful.
    – Brock
    Jun 4, 2020 at 8:35
  • 1
    @Brock thanks! Good to see old posts still helping people! Jun 4, 2020 at 8:44
  • If I later (e.g. in response to a button) add or remove Widgets to/from the Items, the UI does not update. I've played around with additional RaisePropertyChange calls, but had no success. Changing a property (e.g. X or Y) does update the UI, but deleting or adding does not. Any tips for me? I haven't programmed in Windows for decades.
    – Brock
    Jun 4, 2020 at 9:00
  • 1
    @Brock sounds like your Items collection doesn't support INotifyCollectionChanged, try making it of type ObservableCollection<T>. Jun 4, 2020 at 10:44
  • 1
    You the man. I also had to use App.Current.Dispatcher.Invoke((Action)delegate, when modifying the collection, but it now works.
    – Brock
    Jun 4, 2020 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.