2012-11-24 62 views
2

我正在使用Windows 8应用程序。我必须在画布内放置几个控件(图像,矩形)。如果我直接使用它,当我在孩子上使用“Canvas.Left”附加属性(上述控件)时,一切正常。不过,我想使用MVVM。因此,我现在使用像这样的ItemsControl:为ItemsControl项目设置Canvas.Left

<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> 

除了附加的Canvas属性,绑定正在工作。经过一番研究后,我发现这是因为ItemsControl用ContentPresenter封装了它的子节点。因此,我试图让使用解决方案,我就发现了计算器,但没有成功:

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

添加该代码没有设置Canvas.Left属性(甚至去除的DataTemplate中绑定后)。

我错过了什么?提前致谢。

+0

可能与http://stackoverflow.com/questions/11857505/how-do-i-do-bindings-in-itemcontainerstyle-in-winrt有关 – onelaview

回答

0

您的初始代码片段应该不需要设置contentpresenter,因为'ItemTemplate'不需要contentpresenter来呈现。我建议检查你的ViewModel和'MyObjects'中的对象是否实现了IPropertyNotifyChanged。同时检查输出窗口,看看是否有任何绑定问题被报告。

没有看到你如何设置你的视图模型的代码,其中的代码,我不禁进一步。

此外,虽然不是在你的问题,你似乎是在ViewModel中设置查看特定的属性。不是一个好主意 - 视图模型应该是不可知的以查看相关的问题。使用MVVM并不意味着在任何地方使用绑定,应该在控件的xaml或引用样式中显式设置UI控件布局等设置。