Data Binding to Canvas.Left doesn't work
-
1 мая 2012 г. 20:02
I try to bind "Canvas.Left" to my data (<Setter Property="Canvas.Left" Value="{Binding X}" />) but it doesn't work. The getter for "X" and "Y" aren't called. The binding to "Content" works (<TextBlock Text="{Binding Content}" />). The getter for "Content" is called. Therefore I think "ItemsSource" is bound correctly.
What's wrong with "Canvas.Left"?
<ListBox DataContext="{Binding ViewModel}" ItemsSource="{Binding Elements}" Margin="225,402,30,33" > <ListBox.ItemsPanel> <ItemsPanelTemplate> <Canvas Background="LightGray"/> </ItemsPanelTemplate> </ListBox.ItemsPanel> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Content}" /> </DataTemplate> </ListBox.ItemTemplate> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="Canvas.Left" Value="{Binding X}" /> <Setter Property="Canvas.Top" Value="{Binding Y}" /> </Style> </ListBox.ItemContainerStyle> </ListBox>
Thanks for helping,
Andreas Rossi
Все ответы
-
1 мая 2012 г. 20:40
I have found that the way that you are suggesting doesn't work (not sure why, does work in WPF, if I recall correctly doesn't work in Silverlight either). My solution is to create a custom ListBox, like this:
public class CanvasListBox : ListBox { protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { FrameworkElement contentitem = element as FrameworkElement; Binding leftBinding = new Binding() { Path = new PropertyPath("X") }; Binding topBinding = new Binding() { Path = new PropertyPath("Y") }; contentitem.SetBinding(Canvas.LeftProperty, leftBinding); contentitem.SetBinding(Canvas.TopProperty, topBinding); base.PrepareContainerForItemOverride(element, item); } }This is just one of many situations in WinRT where you have to resort to code where data binding should work. Hopefully this can be fixed before RTM.
...Stefan
- Помечено в качестве ответа AnRo 5 мая 2012 г. 17:02
-
5 мая 2012 г. 17:04
Thank You for helping me.
Your code works well.
Andreas
-
24 октября 2012 г. 17:06
I found this helpful, and it doesn't require code behind.
http://stackoverflow.com/questions/889825/is-it-possible-to-bind-a-canvass-children-property-in-xaml
-
25 октября 2012 г. 3:55
I also noticed that embedding a Canvas within another Canvas works, but I don't know whether it's preferred.
<Canvas> <Canvas Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}"> ... </Canvas> </Canvas>

