關於你的第一個問題,這可能是你要尋找的模式:
<ItemsControl>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
</Grid>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<Button Grid.Row="1" Grid.Column="2">R1C2</Button>
<Button Grid.Row="2" Grid.Column="1">R2C1</Button>
<Button Grid.Row="0" Grid.Column="0">R0C0</Button>
</ItemsControl>
在實際應用中,你會設置ItemsControl.ItemsSource
到Binding
源爲對象的集合,然後創建一個DataTemplate
,如:
<DataTemplate DataType="{x:Type MyObject}">
<Rectangle Grid.Row="{Binding Row}" Grid.Column="{Binding Column}">
<!-- other visuals go here -->
</Rectangle>
</DataTemplate>
至於組織代碼放到單獨的文件中有云:你應該考慮,而不是一個用於顯示對象創建一個UserControl
,。創建一個比其他對象更困難,並且UserControl
是生活在他們自己的XAML文件中的類,可以像XAML一樣通過名稱與其他任何對象一起實例化。
根據您的設計,您可能會將網格定位從對象的實際視覺表示中分離出來,以便您可以在其他地方重新使用該表示。這可能是我的方法。創建我的對象UserControl
後,我會創造Grid.Resources
一個DataTemplate
(因爲它是描述如何特定Grid
應顯示對象)是這樣的:
<DataTemplate DataType="{x:Type MyObject}">
<DockPanel Grid.Row="{Binding Row}" Grid.Column="{Binding Column}">
<local:MyObjectUserControl DataContext="{Binding}"/>
</DockPanel>
</DataTemplate>
也有可能XAML使用包括樣組織方法:創建一個包含資源字典一個獨立的XAML文件,然後字典合併到你的窗口(或應用程序,或其他任何東西真的)資源字典:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="myresourcedictionary.xaml"/>
<ResourceDictionary Source="myresourcedictionary2.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
這可以是組織了很多好方法樣式和模板,儘管如此,如果設置了ResourceDictionary.MergedDictionaries
,則不能直接在字典中放置任何項目,因此必須創建一個單獨的XAML文件來包含僅屬於該窗口的資源,這是一種痛苦。
UniformGrid看起來很有前途,但它沒有ItemsSource屬性或支持ItemsPanel/ItemTemplate語法。數據綁定時如何使用它? – Pat 2010-08-27 17:08:17
回答我自己的問題:http://stackoverflow.com/questions/1966258/chessboard-in-wpf/1966620#1966620 – Pat 2010-08-27 18:07:38