要让项目旋转,您应该使用Transforms。在这种情况下,最相关的是旋转变换,为了给它随机分散的外观,我们可以使用ObjectDataProvider 并在其他地方生成我们的角度。
我不了解 VB,但其中涉及的唯一 C# 非常简单,应该很容易移植。
让我们只使用一些简单的东西,比如颜色,可以很容易地切换到图像资源路径。这里我们有一个颜色的 ObservableCollection,还有一个用于生成角度的单独类,它要做的就是返回一个 0 到 360 之间的数字,我们将使用它来旋转每个项目。
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Colors = new ObservableCollection<string>();
Colors.Add("Red");
Colors.Add("Blue");
Colors.Add("Green");
Colors.Add("Yellow");
this.DataContext = this;
}
public ObservableCollection<string> Colors
{
get;
set;
}
}
public class AngleService
{
private static Random rand = new Random();
public int GetAngle()
{
return rand.Next(0, 90);
}
}
在 XAML 中,我们现在可以创建可用于生成角度的资源。
<Window.Resources>
<local:AngleService x:Key="Local_AngleService" />
<ObjectDataProvider x:Key="Local_AngleProvider"
x:Shared="False"
ObjectInstance="{StaticResource Local_AngleService}"
MethodName="GetAngle" />
</Window.Resources>
现在,我们只需要创建一些东西来显示我们的项目。我们可以将它们放在 ListBox 中,并添加一个数据模板来设置每个颜色项的背景,以及应用 RotateTransform。
<ListBox ItemsSource="{Binding Colors}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center">
<ListBox.ItemTemplate>
<DataTemplate>
<Border x:Name="uiItemBorder"
BorderBrush="Black"
BorderThickness="2"
CornerRadius="3"
Background="{Binding}"
Width="50"
Height="50">
<TextBlock Text="{Binding}"
VerticalAlignment="Center"
HorizontalAlignment="Center" />
<Border.RenderTransform>
<RotateTransform Angle="{Binding Source={StaticResource Local_AngleProvider}}" />
</Border.RenderTransform>
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
UI 仍然需要从那里做一些工作,但这应该有助于项目的旋转。