[英]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.