2016-02-24 39 views
0

我正在創建一個WPF應用程序,我必須將一個集合綁定到Canvas,然後,每個元素都顯示爲一個橢圓。所以,因爲我希望能夠按需移動所有元素,所以我將每個元素的視圖模型綁定到Canvas.LeftCanvas.Top。但是,當我將一個新值賦給我的視圖模型的綁定屬性時,橢圓不會移動。如何從ViewModel移動一個橢圓

我的XAML文件:

<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> 

我的視圖模型文件:

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)); 
    } 
} 
. . . 

然後在其他地方:

ShapeCanvasTop = 100; // This does not work 

所以,我在做什麼錯?形狀不移動,但是,屬性ShapeHeightShapeWidth完美地工作,即形狀正確調整大小。

在此先感謝。

回答

1

ItemsControl的項目將包裹在父容器,這就是你需要被設置的位置是什麼:

<ItemsControl.ItemContainerStyle> 
    <Style> 
     <Setter Property="Canvas.Left" Value="{Binding ShapeCanvasLeft}" /> 
     <Setter Property="Canvas.Top" Value="{Binding ShapeCanvasTop}" /> 
    </Style> 
</ItemsControl.ItemContainerStyle> 
+0

這一工程!謝謝! – Dante