Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6385385
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T02:53:33+00:00 2026-05-25T02:53:33+00:00

I want to create a canvas where a user can drop UI elements (representing

  • 0

I want to create a canvas where a user can drop UI elements (representing tasks). He can then drag them to rearrange them. The elements are contained in an ObservableCollection that is the DataContext.

I can set the Left and Top properties of the Canvas, but the objects position is not affected. Any ideas?

Thanks,

Karel

UPDATE:
forgotton ItemsControl descendant (thanks Phil):

 public class CustomItemsCollection    : ItemsControl
{
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
    {            
        FrameworkElement contentitem = element as FrameworkElement;
        // contentitem.HorizontalAlignment = System.Windows.HorizontalAlignment.Left;
        // contentitem.VerticalAlignment = System.Windows.VerticalAlignment.Top;
        Binding leftBinding = new Binding("Left"); 
        leftBinding.Mode = BindingMode.TwoWay;

        contentitem.SetBinding(Canvas.LeftProperty, leftBinding);

        Binding topBinding = new Binding("Top");
        topBinding.Mode = BindingMode.TwoWay;
        contentitem.SetBinding(Canvas.TopProperty, topBinding);
        base.PrepareContainerForItemOverride(element, item);
    }
}

More info:

Binding objects derived from usercontrol provoce an exception so after some googling I created a valueconverter:

public class UIElementWrapper : IValueConverter
{
    private Dictionary<object, object> CollectionsPool = new Dictionary<object, object>();

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value is INotifyCollectionChanged && value is IList)
        {
            ((INotifyCollectionChanged)value).CollectionChanged += UIElementWrapper_CollectionChanged;

            var result = new ObservableCollection<ProxyObject>();
            foreach (var item in (IList)value)
            {
                result.Add(new ProxyObject(item));
            }

            CollectionsPool.Add(result, value);
            return result;
        }
        else
        {
            throw new ArgumentException("value");
        }
    }

    void UIElementWrapper_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (CollectionsPool.ContainsValue(sender))
        {
            foreach (IList result in CollectionsPool.Keys)
            {
                if (CollectionsPool[result] == sender)
                {
                    switch (e.Action)
                    {
                        case NotifyCollectionChangedAction.Add:
                            var index = e.NewStartingIndex;
                            foreach (var item in e.NewItems)
                            {
                                result.Insert(index++, new ProxyObject(item));
                            }
                            break;
                        case NotifyCollectionChangedAction.Remove:
                            foreach (var item in e.OldItems)
                            {
                                var deleteList = new List<ProxyObject>();
                                foreach (ProxyObject p in result)
                                {
                                    if (p.Value == item) deleteList.Add(p);
                                }
                                foreach (var p in deleteList)
                                {
                                    result.Remove(p);
                                }
                            }
                            break;
                        case NotifyCollectionChangedAction.Replace:
                            result[e.OldStartingIndex] = new ProxyObject(e.NewItems[0]);
                            break;
                        case NotifyCollectionChangedAction.Reset:
                            result.Clear();
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

public class ProxyObject
{
    public ProxyObject(object value)
    {
        Value = value;
    }
    public object Value { get; private set; }
}

This works.
But when I bind Left and Top properties of the elements contained in the ObservableCollection they are not used: all items are placed at position 0,0

Here is the code behind:

public MainPage()
    {
        InitializeComponent();

        ObservableCollection<Border> items = new ObservableCollection<Border>();
        double left = 0.0;
        double top = 0.0;
        int i = 0;
        Border item = (Border)XamlReader.Load(
           "<Border Background=\"Green\" Height=\"140\" Width=\"180\"  xmlns=\"http://schemas.microsoft.com/client/2007\"></Border>");
        item.Name = string.Format("name {0}", i);
        item.SetValue(Canvas.LeftProperty, left);
        item.SetValue(Canvas.TopProperty, top);
        items.Add(item);

        i++;
        left += 200;
        top += 150;
        item = (Border)XamlReader.Load(
            "<Border Background=\"Yellow\" Margin=\"160, 120, 0, 0\" Height=\"120\" Width=\"160\"  xmlns=\"http://schemas.microsoft.com/client/2007\"></Border>");
        item.Name = string.Format("name {0}", i);
        item.SetValue(Canvas.LeftProperty, left);
        item.SetValue(Canvas.TopProperty, top);
        items.Add(item);

        i++;
        left += 170;
        top += 130;
        item = (Border)XamlReader.Load(
            "<Border Background=\"Red\" Height=\"60\" Width=\"80\"  xmlns=\"http://schemas.microsoft.com/client/2007\"></Border>");
        item.Name = string.Format("name {0}", i);
        item.SetValue(Canvas.LeftProperty, left);
        item.SetValue(Canvas.TopProperty, top);
        items.Add(item);

        left += 90;
        top += 70;
        item = (Border)XamlReader.Load(
            "<Border Background=\"Blue\" Height=\"30\" Width=\"40\"  xmlns=\"http://schemas.microsoft.com/client/2007\"></Border>");
        item.Name = string.Format("name {0}", i);

        item.SetValue(Canvas.LeftProperty, left);
        item.SetValue(Canvas.TopProperty, top);
        items.Add(item);



        try
        {
            // this.customItemsCollection1.ItemsSource = items;
            LayoutRoot.DataContext = items;
        }
        catch (Exception ex)
        {
            textBlock1.Text = ex.Message;
        }
    }

and here is the xaml:

<UserControl x:Class="ItemsControlTestProject.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:lh="clr-namespace:ItemsControlTestProject.Helpers"
         mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="560" xmlns:my="clr-namespace:ItemsControlTestProject">


<UserControl.Resources>
        <lh:UIElementWrapper x:Key="UIElementWrapper"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="AntiqueWhite">
            <my:CustomItemsCollection Canvas.Left="0" Canvas.Top="0" Background="Coral" x:Name="customItemsCollection1" Margin="0,0,0,0" Width="532" ItemsSource="{Binding Converter={StaticResource UIElementWrapper}}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas   Background="LightGoldenrodYellow" Canvas.Left="0" Canvas.Top="0" Width="350" Height="350"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <ContentPresenter Content="{Binding Value}"  Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
        </my:CustomItemsCollection>
            <TextBlock  Height="61" Name="textBlock1" Text="TextBlock" AllowDrop="True" Width="526" Canvas.Left="6" Canvas.Top="367" Margin="20,388,14,0" />        
    </Grid>
</UserControl>





<UserControl.Resources>
        <lh:UIElementWrapper x:Key="UIElementWrapper"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="AntiqueWhite">
            <my:CustomItemsCollection Canvas.Left="0" Canvas.Top="0" Background="Coral" x:Name="customItemsCollection1" Margin="0,0,0,0" Width="532" ItemsSource="{Binding Converter={StaticResource UIElementWrapper}}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <Canvas   Background="LightGoldenrodYellow" Canvas.Left="0" Canvas.Top="0" Width="350" Height="350"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <ContentPresenter Content="{Binding Value}"  Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" />
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
        </my:CustomItemsCollection>
            <TextBlock  Height="61" Name="textBlock1" Text="TextBlock" AllowDrop="True" Width="526" Canvas.Left="6" Canvas.Top="367" Margin="20,388,14,0" />        
    </Grid>
</UserControl>
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T02:53:33+00:00Added an answer on May 25, 2026 at 2:53 am

    The problem is that you set the dependency property Canvas.Top prior to binding it, by adding it to the collection. Before this “Add” the object you are binding has no property Canvas.Top

    Just change the order

    items.Add(item);
    item.SetValue(Canvas.LeftProperty, left);
    item.SetValue(Canvas.TopProperty, top);
    

    ..and it should work

    /Nykkel

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want create a drop shadow around the canvas component in flex. Technically speaking
I want to create some text in a canvas: myText = self.canvas.create_text(5, 5, anchor=NW,
I want to create an application which main window has canvas (or something where
I am working on something similar to a canvas, users can add drag labels
I want to create a canvas which shows ads for like 10 sec and
I am trying to create a canvas in Android where we can use it
We want to create a subclass of Canvas that only allows children of a
My intention is simple. Create a sort-of panel where the user can scroll through
The scenario is that i want the user to create a shape in a
I want create a excel with Apache POI in java and I must insert

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.