WinRT ItemsControl与Grid列和行

时间:2012-09-26 22:11:45

标签: c# xaml windows-8 microsoft-metro itemscontrol

我是XAML的新手。我搜索了ItemsControl并找到了一个易于理解的教程,但问题是它在WinRT中不起作用。

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

我尝试在TargetType标记中使用Style,但是,在运行时我遇到了异常。

<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 个答案:

答案 0 :(得分:3)

你的问题在这里:

<Style TargetType="TextBox">

这应该是:

<Style TargetType="ContentPresenter">

ItemContainer的{​​{1}}为ItemsControl(除非特定项目已添加到ContentPresenter)。

因此,您的视图层次结构看起来像这样(假设您没有将ItemsControl更改为ItemsPanel以外的其他内容):

StackPanel

编辑:

Scott在评论中指出,这个解决方案实际上并不适用于WinRT。我做了类似的事情,你可以修改它来做适当的绑定:

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

这会将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属性,类似于XCanvas.TopProperty属性。