2012-09-26 31 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