所以,我的问题是我试图在画布中移动一些用户控件。
这实际上工作得很好,只要鼠标指针在停靠面板内,这是用户控件的组成部分。但是,在停靠面板中,有几个项目控件,如果我单击它们并尝试移动它,则会生成一个异常,指出“无法将类型为“System.String”的对象转换为类型“UMLDesigner.Model” .Node”。这是有道理的,但是有没有办法获取 DockPanel,而不是 Itemscontrol,即使它是单击的 itemscontrol?
有相关的C#代码:
public void MouseMoveNode(MouseEventArgs e)
{
//Is the mouse captured?
if (Mouse.Captured != null)
{
FrameworkElement movingClass = (FrameworkElement)e.MouseDevice.Target;
Node movingNode = (Node)movingClass.DataContext;
Canvas canvas = FindParent<Canvas>(movingClass);
Point mousePosition = Mouse.GetPosition(canvas);
if (moveNodePoint == default(Point)) moveNodePoint = mousePosition;
movingNode.X = (int)mousePosition.X;
movingNode.Y = (int)mousePosition.Y;
}
}
public void MouseUpNode(MouseEventArgs e)
{
//Used to move node
FrameworkElement movingClass = (FrameworkElement)e.MouseDevice.Target;
Node movingNode = (Node)movingClass.DataContext;
Canvas canvas = FindParent<Canvas>(movingClass);
Point mousePosition = Mouse.GetPosition(canvas);
new MoveNodeCommand(movingNode, (int)mousePosition.X, (int)mousePosition.Y, (int)moveNodePoint.X, (int)moveNodePoint.Y);
moveNodePoint = new Point();
e.MouseDevice.Target.ReleaseMouseCapture();
}
还有一些用户控件的xaml:
<DockPanel.Background>
<LinearGradientBrush StartPoint="0,0" EndPoint="1,0.0">
<LinearGradientBrush.GradientStops>
<GradientStop Color="Azure" Offset="0"/>
<GradientStop Color="Transparent" Offset="1"/>
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</DockPanel.Background>
<TextBox Text="{Binding ClassName}" HorizontalAlignment="Center" DockPanel.Dock="Top" Margin="5,0,5,0"/>
<!--Note the " : " is acutally being written to the GUI-->
<ItemsControl Name="attributeList" ItemsSource="{Binding Attributes}" Margin="5,0,5,0" DockPanel.Dock="Top">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock><Run Text="{Binding Path=.}"/> : <Run Text="Type her"/></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<ItemsControl Name="propertiesList" ItemsSource="{Binding Properties}" Margin="5,0,5,0" DockPanel.Dock="Top">
</ItemsControl>
<ItemsControl Name="methodsList" ItemsSource="{Binding Methods}" Margin="5,0,5,0" DockPanel.Dock="Top">
<ItemsControl.ItemTemplate>
<DataTemplate>
<TextBlock><Run Text="{Binding Path=.}"/>() : <Run Text="Type her"/></TextBlock>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</DockPanel>
我当然也想知道是否有更聪明或更好的方法来做到这一点。