Canvas TwoWay Biding for ItemsControl内的坐标

时间:2018-01-31 21:20:18

标签: c# .net wpf xaml canvas

我有一个ItemsControl,其ItemSource为Entities,是ObservableCollection<Entity>

Entity类包含字符串NameX,Ypublic {get;set;}

的属性
<ItemsControl  x:Name="myCanvas" Grid.Row="1" ItemsSource="{Binding Path=Entities}" MouseMove="myCanvas_MouseMove" MouseDoubleClick="myCanvas_MouseDoubleClick" MouseUp="myCanvas_MouseUp" MouseDown="myCanvas_MouseDown" >
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
          <Setter Property="Canvas.Left" Value="{Binding Path=Y,Mode=TwoWay}"  />
            <Setter Property="Canvas.Top" Value="{Binding Path=X,Mode=TwoWay}" />
        </Style>
    </ItemsControl.ItemContainerStyle>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Rectangle Width="50" Height="50" RadiusX="4" RadiusY="4" Stroke="Black" Fill="Red" />
                <Label Content="{Binding Path=Name}"/>
            </Grid>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

当我在我的集​​合中添加新的Entity时,我可以正常看到UI中的更改。我想通过鼠标移动那些矩形,这就是为什么我在ItemsControl的发布事件中捕获鼠标位置并更改我的集合Entity中的Entities位置但我看不到任何用户界面的变化。

MouseUp事件

private void myCanvas_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    Point point = Mouse.GetPosition(sender as FrameworkElement);
    if (e.LeftButton == MouseButtonState.Released)
    {
        Entities[tempIndex].X = (int)point.X;
        Entities[tempIndex].Y = (int)point.Y;           
    }
    var binding = new Binding { Source = Entities };
    myCanvas.SetBinding(ItemsControl.ItemsSourceProperty, binding);
}

tempIndex是我要移动的Entity

1 个答案:

答案 0 :(得分:1)

你的Canvas.Left绑定到Y(应该是X)。

你的Canvas.Top绑定到X(应该是Y)。

克莱门斯是正确的。不需要在代码中为ItemsSource设置绑定。

以下是将实体#2移动到您在myCanvas上单击的位置的一些代码。我没有实现整个拖放,只是将实体移动到您单击的位置。我在顶部添加了一个数据网格,以显示实体的值。

MainWindow.xaml

form

MainWindow.xaml.cs

<h:form id="carForm" binding="#{carForm}">
    <!-- Your code here.... -->
    <p:droppable for="selectedCars" tolerance="touch"
        activeStyleClass="ui-state-highlight" datasource="availableCars"
        onDrop="handleDrop">
        <p:ajax listener="#{dndCarsView.onCarDrop}"
            update="dropArea availableCars" form="#{carForm.clientId}" />
    </p:droppable>
</h:form>
相关问题