This is what I'm trying to accomplish:
I want to have a canvas that supports dragging and dropping arbitrary data in the style of Microsoft Visio. I've found this link that does that: http://www.codeproject.com/KB/WPF/WPFDiagramDesigner_Part1.aspx
However, I also want to hydrate the canvas at run-time. I found this post: https://stackoverflow.com/questions/889825/wpf-is-it-possible-to-bind-a-canvass-children-property-in-xaml
One of the solutions suggests drawing each item on it's own Canvas, which I've gotten to work. But I can't get it drag and drop to work by binding the data to an ItemControl child of the canvas. Ideally, I'd like to avoid having to use code-behind to do this. Is there a XAML solution using everything I have? My code follows:
This is the MoveThumb that I created to be the control that actually is moved.
class MoveThumb : Thumb
{
public MoveThumb()
{
DragDelta += new DragDeltaEventHandler(this.MoveThumb_DragDelta);
}
private void MoveThumb_DragDelta(object sender, DragDeltaEventArgs e)
{
Control item = this.DataContext as Control;
if (item != null)
{
double left = Canvas.GetLeft(item);
double top = Canvas.GetTop(item);
Canvas.SetLeft(item, left + e.HorizontalChange);
Canvas.SetTop(item, top + e.VerticalChange);
}
}
}
This are the xaml templates I defined per the first link.
<ControlTemplate x:Key="MoveThumbTemplate" TargetType="{x:Type t:MoveThumb}">
<Rectangle Fill="Gray"/>
</ControlTemplate>
<ControlTemplate x:Key="NodeItemTemplate">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<t:MoveThumb Template="{StaticResource MoveThumbTemplate}"
Cursor="SizeAll"/>
<ContentPresenter Content="{TemplateBinding ContentControl.Content}"/>
</Grid>
</ControlTemplate>
<DataTemplate x:Key="nodeTemplate" DataType="Node">
<ContentControl Name="NodeItem"
Width="50"
Height="50"
Canvas.Top="50"
Canvas.Left="50"
Template="{StaticResource NodeItemTemplate}">
<Ellipse Fill="Black" IsHitTestVisible="False"/>
</ContentControl>
</DataTemplate>
This is the xaml to create and bind my ItemsControl in the canvas.
<ItemsControl ItemsSource="{Binding Path=NodeCollection}" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="Yellow" Width="auto" Height="auto" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<ContentControl Name="NodeItem"
Width="50"
Height="50"
Canvas.Top="100"
Canvas.Left="100"
Template="{StaticResource NodeItemTemplate}">
<Ellipse Fill="Black" IsHitTestVisible="False"/>
</ContentControl>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ItemContainerStyle>
<Style>
<Setter Property="Canvas.Top" Value="{Binding Path=Y}" />
<Setter Property="Canvas.Left" Value="{Binding Path=X}" />
</Style>
</ItemsControl.ItemContainerStyle>
</ItemsControl>