2

I'm working on a Windows 8 app. I have to place several controls (images, rectangles) inside a Canvas. If I do it directly, everything is fine when I'm using "Canvas.Left" attached property on the children (the mentioned controls). However, I'd like to use MVVM. Therefore I now use an ItemsControl like this:

    <ItemsControl ItemsSource="{Binding MyObjects}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <Image Source="{Binding Image}" Visibility="{Binding IsImage, Converter={StaticResource boolConverter}}" />
                    <Rectangle Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}" Width="{Binding Width}" Height="{Binding Height}" Fill="{Binding Fill}" Visibility="{Binding IsNoImage, Converter={StaticResource boolConverter}}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

Binding is working except for the attached Canvas properties. After some research I found out that's because of ItemsControl wrapping its children with a ContentPresenter. Therefore I tried to make use a solution I found on stackoverflow, but without success:

<ItemsControl.ItemContainerStyle>
   <Style TargetType="ContentPresenter">
       <Setter Property="Canvas.Left" Value="{Binding Left}" />
   </Style>
</ItemsControl.ItemContainerStyle>

Adding this code doesn't set the Canvas.Left property (even after removing the binding from the DataTemplate).

What am I missing? Thanks in advance.

Sentropie
  • 249
  • 1
  • 4
  • 14
  • May be related to http://stackoverflow.com/questions/11857505/how-do-i-do-bindings-in-itemcontainerstyle-in-winrt – onelaview Feb 25 '16 at 09:01

1 Answers1

0

Your initial code snippet should work without setting a contentpresenter, as 'ItemTemplate' doesn't need a contentpresenter to render. I would recommend checking that both your ViewModel and the objects held within 'MyObjects' are implementing IPropertyNotifyChanged. Also check the Output window to see if there are any binding issues being reported.

Without seeing the code on how you are setting your viewmodel, and the code within it I cannot help further.

Additionally, although not in your question, it seems you are setting View specific properties in your ViewModel. NOT a good idea - view models should be agnostic to view related concerns. Using MVVM doesn't mean using binding everywhere and things like setting UI control layouts should be explicitly set in the control's xaml or a referenced style.

Patrick McCurley
  • 2,006
  • 1
  • 14
  • 24