2010-11-22 93 views
4

我有一個表Item,它由3米欄:WPF二維DataGrid/ListView?

ItemId int PK 
RoomId int FK 
UnitId int FK 
Cost money 

我希望有具有動態生成的列和行代表下列樞軸一個DataGrid/ListView中:

 Room1 Room2 Room3 Room4 
Unit1 $34 $72 $48 $98 
Unit2 $64 $56 $67 $24 
Unit3 $24 $34 $34 $34 

我更喜歡控制或助手到現有的一個,而不是一個骯髒的功能,因爲我會需要這個場景很多,但任何東西都熱烈歡迎。

我想要有Room1Unit1等行和列標題,並相應地生成/設置單元格。

回答

8

首先,你需要你的Item對象的集合轉換成適合的收集:

var dict = data.Select(i => i.UnitId).Distinct() 
    .ToDictionary(u => u, u => data 
     .Where(i => i.UnitId == u) 
     .ToDictionary(d => d.RoomId, d => d)); 
var rooms = dict.Values.First().Keys; 
DataContext = Tuple.Create(dict, rooms); 

,然後你需要用正確的DataTemplate配置的ItemsControl

<Grid> 
    <Grid.RowDefinitions> 
    <RowDefinition Height="Auto" /> 
    <RowDefinition Height="Auto" /> 
    </Grid.RowDefinitions> 
    <ItemsControl ItemsSource="{Binding Item2}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
     <StackPanel Orientation="Horizontal" 
        Margin="80,0,0,0" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <TextBlock HorizontalAlignment="Center" 
        Foreground="Blue" 
        Width="80" 
        Margin="5"> 
         <Run Text="Room" /> 
         <Run Text="{Binding Mode=OneWay}" /> 
     </TextBlock> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    </ItemsControl> 
    <ItemsControl ItemsSource="{Binding Item1}" 
       AlternationCount="{Binding Count}" 
       Grid.Row="1"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
     <StackPanel Orientation="Horizontal"> 
      <TextBlock VerticalAlignment="Center" 
        Foreground="Blue" 
        Width="80"> 
         <Run Text="Unit" /> 
         <Run Text="{Binding Key, Mode=OneWay}" /> 
      </TextBlock> 
      <ItemsControl ItemsSource="{Binding Value}" 
         VerticalAlignment="Center"> 
      <ItemsControl.ItemsPanel> 
       <ItemsPanelTemplate> 
       <StackPanel Orientation="Horizontal" /> 
       </ItemsPanelTemplate> 
      </ItemsControl.ItemsPanel> 
      <ItemsControl.ItemTemplate> 
       <DataTemplate> 
       <TextBlock Text="{Binding Path=Value.Cost, StringFormat={}{0:C}}" 
          Margin="5" 
          Width="80" /> 
       </DataTemplate> 
      </ItemsControl.ItemTemplate> 
      </ItemsControl> 
     </StackPanel> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
    </ItemsControl> 
</Grid> 

,然後你得到這個:

alt text

+0

太棒了!要命!你認爲我可以使用DataGridColumnHeader和DataGridRowHeader作爲頭文件嗎? 我想我正在尋找一個繼承Selector或MultiSelector的自定義控件,它應該有一個ColumnItemsSource,RowItemsSource和一個事件GeneratingCell,它的EventArgs提供了當前的單元格Item + Unit,並且我必須提供生成單元格的DataContext的屬性,它會根據CellDataTemplate屬性生成單元格。但由於我沒有開發定製控件的嚴肅經驗,所以我很難從頭開始。 – Shimmy 2010-11-23 10:52:08