1

I'm creating a WPF application where I have to bind a collection to a Canvas, then, each element is showed as an ellipse. So, since I want to be able to move all the elements on demand I bound each element's viewmodel to Canvas.Left and Canvas.Top. However, when I assign a new value to my viewmodel's bound properties the ellipse does not move.

My xaml file:

<ItemsControl ItemsSource="{Binding Elements}">                   
<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Viewbox >
            <Grid>
                <Ellipse Stroke="Black" 
                         Width="{Binding ShapeWidth, Mode=TwoWay}" 
                         Height="{Binding ShapeHeight, Mode=TwoWay}" 
                         Canvas.Left="{Binding ShapeCanvasLeft, Mode=TwoWay}"
                         Canvas.Top="{Binding ShapeCanvasTop, Mode=TwoWay}"
                         Fill="{Binding Background}"
                         />                
                <TextBlock Text="{Binding ElementName}"
                           HorizontalAlignment="Center"  
                           TextAlignment="Center" 
                           VerticalAlignment="Center"
                           />
            </Grid>
        </Viewbox>
    </DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Canvas />
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

My viewmodel file:

public double ShapeCanvasLeft
{
    get
    {
        return m_shapeCanvasLeft;
    }
    set
    {
        m_shapeCanvasLeft = value;
        OnPropertyChanged(nameof(ShapeCanvasLeft));
    }
}

public double ShapeCanvasTop
{
    get
    {
        return m_shapeCanvasTop;
    }
    set
    {
        m_shapeCanvasTop = value;
        OnPropertyChanged(nameof(ShapeCanvasTop));
    }
}
. . .

Then in some other place:

ShapeCanvasTop = 100; // This does not work

So, what am I doing wrong? The shape does not move, however, the properties ShapeHeight and ShapeWidth work perfectly, i.e. the shape resizes correctly.

Thanks in advance.

1 Answer 1

1

ItemsControl items get wrapped in a parent container, that's what you need to be setting the position of:

<ItemsControl.ItemContainerStyle>
    <Style>
        <Setter Property="Canvas.Left" Value="{Binding ShapeCanvasLeft}" />
        <Setter Property="Canvas.Top" Value="{Binding ShapeCanvasTop}" />
    </Style>
</ItemsControl.ItemContainerStyle>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.