1

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

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

我尝试TargetTypeStyle标签中使用,但是,在运行时出现异常。

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

1 回答 1

3

你的问题在这里:

<Style TargetType="TextBox">

这应该是:

<Style TargetType="ContentPresenter">

ItemContainerfor anItemsControl是 a (除非将ContentPresenter特定项目添加到ItemsControl)。

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

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

编辑:

As Scott pointed out in the comments, this solution doesn't actually work for WinRT. I did something similar and you can probably modify it to do the appropriate binding:

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 });
        }
    }
}

This binds the Canvas.LeftProperty to the X property on each item in the collection and similarly the Canvas.TopProperty and the Y property.

于 2012-09-27T03:09:00.063 回答