Dante
Dante

Reputation: 3316

How to move an Ellipse from ViewModel

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.

Upvotes: 1

Views: 535

Answers (1)

Mark Feldman
Mark Feldman

Reputation: 16119

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>

Upvotes: 1

Related Questions