如何使用拖放来移动网格中的元素。
即我有一个由 5x3 元素组成的网格,我希望能够从网格中拖动一个元素(通常是一个按钮)并让它在网格中的其他位置放置。
最好有一些突出显示或移动来查看按钮将插入的位置。
目前我只看到代码隐藏中的方法,但肯定有更好的方法,更 MVVM 的方法......
为清楚起见:它是一个 Windows 桌面应用程序
我的网格嵌入在一个列表框中,正如您从我的 XAML 中看到的那样:
<ListBox Margin="0" BorderThickness="0" Padding="0" Grid.Row="1" Background="Lime" SelectionMode="Single" ItemsSource="{Binding Path=CurrentToolTablet.Tools}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled" VerticalContentAlignment="Stretch" HorizontalContentAlignment="Stretch">
<ListBox.Template>
<ControlTemplate TargetType="{x:Type ListBox}">
<Border x:Name="Bd"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
SnapsToDevicePixels="true">
<ScrollViewer Focusable="false" Padding="{TemplateBinding Padding}">
<ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
</ScrollViewer>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
</Trigger>
<Trigger Property="IsGrouping" Value="true">
<Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
</Grid>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Button Focusable="False" Command="{Binding CmdClickTool}" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Col}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
<Image Source="myimage.png" Grid.Row="{Binding Path=Row}" Grid.Column="{Binding Path=Col}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0">
</Image>
</Button>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style>
<Setter Property="Grid.Column" Value="{Binding Path=Col}"/>
<Setter Property="Grid.Row" Value="{Binding Path=Row}"/>
<Setter Property="ContentControl.HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="ContentControl.VerticalContentAlignment" Value="Stretch"/>
<Setter Property="ContentControl.Margin" Value="0"/>
<Setter Property="ContentControl.Padding" Value="0"/>
<Setter Property="Control.BorderThickness" Value="0"/>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>