I have an ItemsControl
with an .ItemsPanel>
that has a <Canvas>
. What I want to do is to bind Canvas.Left
and Canvas.Top
from the .ItemContainerStyle>
to an .ItemTemplate>
<DataTemplate>
that has a custom control with a read-only DependencyProperty
.
Here is my XAML code that I have tried:
<ItemsControl x:Name="itemsControl" ItemsSource="{Binding CanvasObjectModels}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Width="1000" Height="1000" Background="GhostWhite"
MouseDown="Canvas_MouseDown"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemContainerStyle>
<Style TargetType="ContentPresenter">
<Setter Property="Canvas.Left" Value="{Binding ElementName=NodeTemplate, Path=ActualOrigin.X}" />
<Setter Property="Canvas.Top" Value="{Binding ElementName=NodeTemplate, Path=ActualOrigin.Y}" />
</Style>
</ItemsControl.ItemContainerStyle>
<ItemsControl.ItemTemplate>
<DataTemplate>
<CanvasObject:Node x:Name="NodeTemplate" Origin="{Binding Origin}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
The MouseDown event sends the Point data to the ViewModel to add to the ObservableCollection
CanvasObjectModels Origin property. When the Origin is set, the <Node>
will set the read-only ActualOrigin DependencyProperty
. I have verified that ActualOrigin is indeed set properly. However, as this code stands right now, the <Node>
is set only at 0,0 on the <Canvas>
.
It would appear that a similar question was asked Wpf bind property in ItemContainerStyle to TextBlock in DataTemplate of ItemTemplate, however, this example is not the same scenario and doesn't really show how to address my concern. It does however seem to suggest that I could set the Canvas.Left
and Canvas.Top
properties directly in the <Node>
tag with the binding but I got the same results when I tried that as well.
Also of note, I got an error when executing the code:
System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=NodeTemplate'. BindingExpression:Path=ActualOrigin.X; DataItem=null; target element is 'ContentPresenter' (Name=''); target property is 'Left' (type 'Double')
Other than it cannot find the source for binding, I am uncertain what this means.
Somehow I do not think the name I applied to the <CanvasObject:Node>
is being accessed by the .ItemContainerStyle>
tag.
The answer to this post might shed some light to my problem: Binding an attached property to an item in ItemsControl with custom panel problem, but their scenario also is sort of different from mine because I am not using a custom panel.
Any help would be greatly appreciated.