[英]WinRT ItemsControl with Grid columns and rows
我是XAML的新手。 我搜索了ItemsControl并找到了一个易于理解的教程,但问题是它在WinRT中不起作用。
教程: 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>
你的问题在这里:
<Style TargetType="TextBox">
这应该是:
<Style TargetType="ContentPresenter">
ItemsControl
的ItemContainer
是ContentPresenter
(除非将特定项添加到ItemsControl
)。
因此,您的视图层次结构看起来像这样(假设您没有将ItemsPanel
更改为除StackPanel
之外的其他内容):
<StackPanel>
<ContentPresenter>
<TextBox/>
</ContentPresenter>
</StackPanel>
编辑:
正如斯科特在评论中指出的那样,这个解决方案实际上并不适用于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.TopProperty
和Y
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.