Using MouseDragElementBehavior with an ItemsControl and Canvas

假如想象 提交于 2019-12-02 02:21:17

I don't really know the blend sdk behaviours, but I've worked with behaviours in general, so I hope the same mechanisms apply.

If you want to add a behaviour to the controls created by an ItemsControl the best way is adding it via a setter in the ItemsControl.ItemContainerStyle, though in this case I found it easier to add it in the ItemsControl.ItemTemplate

Something like

        <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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!