将MouseDragElementBehavior与ItemsControl和Canvas结合使用
问题描述:
我当前在使用ItemsControl和自定义画布时从Blend SDK使用MouseDragElementsBehavior时出现问题。我的自定义画布根据DependencyProperty简单地向它的子项添加或删除MouseDragElement。当我手动将Items添加到画布的子项时,这很好,但在移动到ItemsControl时似乎已经损坏。将MouseDragElementBehavior与ItemsControl和Canvas结合使用
我目前使用下面的ItemsControl代码:
<ItemsControl ItemsSource="{Binding Path=CanvasItems}">
<ItemsControl.DataContext>
<ViewModels:ViewModel/>
</ItemsControl.DataContext>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<my:CustomCanvas Background="Black" IsEditable="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.CanEdit}" AllowDrop="{Binding RelativeSource={RelativeSource Self}, Path=IsEditable}" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
添加在Canvas.VisualChildrenChanged方法拖动行为不允许新创建的对象被移动像以前一样。
是否需要将拖动行为添加到传递给VisualChildrenChanged的ContentPresenter或提供特殊样式的内容之外?
答
我并不真正了解混合sdk行为,但我一般都使用过行为,所以我希望应用相同的机制。
如果你想添加一个行为由一个ItemsControl创建的控制最好的办法是通过在ItemsControl.ItemContainerStyle二传手加入它,但在这种情况下,我发现它更容易将其添加在ItemsControl.ItemTemplate
喜欢的东西
<ItemsControl ItemsSource="{Binding CanvasItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Transparent" AllowDrop="True" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Green" BorderThickness="1" Background="AntiqueWhite">
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior ConstrainToParentBounds="True" DragBegun="MouseDragElementBehavior_DragBegun"/>
</i:Interaction.Behaviors>
<ContentControl Content="{Binding}" />
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
答
<ItemsControl ItemsSource="{Binding CanvasItems}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="YourControl">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="YourControl">
<Border>
<Grid>
<SystemWindowsInteractivity:Interaction.Behaviors>
<MicrosoftExpressionInteractivityLayout:MouseDragElementBehavior />
</SystemWindowsInteractivity:Interaction.Behaviors>
<ContentPresenter />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>
这会,如果我在做一个拖/放(已implmented)工作... DragMouseElement用于在其容器中移动的对象。 – JMcCarty 2011-06-15 15:25:46
不幸的是,我没有Blend,所以我无法测试代码。但我仍然会假设,MouseDragElementBehaviour会修改它附加的控件的Canvas.X附加属性,所以它仍然应该工作。项目容器样式应用于由ItemsControl生成的所有容器。我编辑了代码以反映我见过的混合行为的样本。 – 2011-06-15 16:36:28
您提供的样式导致参数计数不匹配错误。你碰巧记得你在哪里看到这些样品,以便我可以看看? – JMcCarty 2011-06-15 17:43:30