2012-11-24 108 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控件佈局等設置。