2012-09-26 32 views
1

我是XAML的新手。我搜索了ItemsControl,並找到了一個易於理解的教程,但問題在於它不適用於WinRT。帶網格列和行的WinRT ItemsControl

教程:https://rachel53461.wordpress.com/2011/09/17/wpf-itemscontrol-example/

我試圖Style標籤使用TargetType,然而,在運行時我得到了一個例外。

<ItemsControl ItemsSource="{Binding MyCollection}"> 
    <!-- ItemsPanelTemplate --> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <Grid> 
       <Grid.RowDefinitions> 
        <RowDefinition /> 
        <RowDefinition /> 
        <RowDefinition /> 
        <RowDefinition /> 
        <RowDefinition /> 
        <RowDefinition /> 
       </Grid.RowDefinitions> 
       <Grid.ColumnDefinitions> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
        <ColumnDefinition /> 
       </Grid.ColumnDefinitions> 
      </Grid> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 

    <!-- ItemContainerStyle --> 
    <ItemsControl.ItemContainerStyle> 
     <Style TargetType="TextBox"> 
      <Setter Property="Grid.Column" 
       Value="{Binding xIndex}" /> 
      <Setter Property="Grid.Row" 
       Value="{Binding yIndex}" /> 
     </Style> 
    </ItemsControl.ItemContainerStyle> 

    <!-- ItemTemplate --> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <TextBox Background="{Binding color}" Text="{Binding xIndex,Mode=OneWay}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
+1

請添加例外的詳細信息。 – akton

回答

3

你的問題是在這裏:

<Style TargetType="TextBox"> 

這是什麼是應該是:

<Style TargetType="ContentPresenter"> 

ItemContainerItemsControlContentPresenter(除非特定項目被添加到ItemsControl)。

所以你的視圖層次看起來是這樣的(假設你沒有改變ItemsPanel比一個StackPanel其他東西):

<StackPanel> 
    <ContentPresenter> 
     <TextBox/> 
    </ContentPresenter> 
</StackPanel> 

編輯:

正如Scott在評論中指出,這個解決方案實際上並不適用於WinRT。我做了類似的事情,你或許可以修改它做相應的綁定:

public class CustomItemsControl : ItemsControl 
{ 
    protected override void PrepareContainerForItemOverride(DependencyObject element, object item) 
    { 
     base.PrepareContainerForItemOverride(element, item); 
     FrameworkElement source = element as FrameworkElement; 
     if (source != null) 
     { 
      source.SetBinding(Canvas.LeftProperty, new Binding { Path = new PropertyPath("X"), Mode = BindingMode.TwoWay }); 
      source.SetBinding(Canvas.TopProperty, new Binding { Path = new PropertyPath("Y"), Mode = BindingMode.TwoWay }); 
     } 
    } 
} 

此綁定Canvas.LeftProperty到集合中的X財產上的每個項目,同樣的Canvas.TopPropertyY財產。

+0

它毫無例外地運行,但它不使用列和行屬性。 – user1701616

+0

現在即時在每個元素上使用帶有邊距的畫布,但這不是我真正想要的,如果我的問題不明確,我可以顯示更多代碼。 – user1701616

+0

「邊距」在畫布中不起作用。你需要做一些像Canvas.Left =「30」Canvas.Top =「30」'來設置畫布內控件的絕對位置。 – mydogisbox