Dot-Net

如何基於二維數組填充 WPF 網格

  • November 10, 2008

我有一個二維對像數組,我基本上想將每個對像數據綁定到 WPF 網格中的一個單元格。目前我有這個工作,但我大部分都是按程序完成的。我創建正確數量的行和列定義,然後循環單元格並創建控制項並為每個控制項設置正確的綁定。

至少我希望能夠使用模板來指定 xaml 中的控制項和綁定。理想情況下,我想擺脫程式碼,只使用數據綁定來完成這一切,但我不確定這是否可能。

這是我目前正在使用的程式碼:

public void BindGrid()
{
   m_Grid.Children.Clear();
   m_Grid.ColumnDefinitions.Clear();
   m_Grid.RowDefinitions.Clear();

   for (int x = 0; x < MefGrid.Width; x++)
   {
       m_Grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star), });
   }

   for (int y = 0; y < MefGrid.Height; y++)
   {
       m_Grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star), });
   }

   for (int x = 0; x < MefGrid.Width; x++)
   {
       for (int y = 0; y < MefGrid.Height; y++)
       {
           Cell cell = (Cell)MefGrid[x, y];                    

           SolidColorBrush brush = new SolidColorBrush();

           var binding = new Binding("On");
           binding.Converter = new BoolColorConverter();
           binding.Mode = BindingMode.OneWay;

           BindingOperations.SetBinding(brush, SolidColorBrush.ColorProperty, binding);

           var rect = new Rectangle();
           rect.DataContext = cell;
           rect.Fill = brush;
           rect.SetValue(Grid.RowProperty, y);
           rect.SetValue(Grid.ColumnProperty, x);
           m_Grid.Children.Add(rect);
       }
   }

}

Grid 的目的不是為了真正的數據綁定,它只是一個面板。我列出了完成二維列表視覺化的最簡單方法

<Window.Resources>
   <DataTemplate x:Key="DataTemplate_Level2">
           <Button Content="{Binding}" Height="40" Width="50" Margin="4,4,4,4"/>
   </DataTemplate>

   <DataTemplate x:Key="DataTemplate_Level1">
       <ItemsControl ItemsSource="{Binding}" ItemTemplate="{DynamicResource DataTemplate_Level2}">
           <ItemsControl.ItemsPanel>
               <ItemsPanelTemplate>
                   <StackPanel Orientation="Horizontal"/>
               </ItemsPanelTemplate>
           </ItemsControl.ItemsPanel>
       </ItemsControl>
   </DataTemplate>

</Window.Resources>
<Grid>
   <ItemsControl x:Name="lst" ItemTemplate="{DynamicResource DataTemplate_Level1}"/>
</Grid>

並且在後面的程式碼中使用 TwoDimentional 資料結構設置 lst 的 ItemsSource。

 public Window1()
   {
       List<List<int> lsts = new List<List<int>();

       for (int i = 0; i < 5; i++)
       {
           lsts.Add(new List<int>());

           for (int j = 0; j < 5; j++)
           {
               lsts[i].Add(i * 10 + j);
           }
       }

       InitializeComponent();

       lst.ItemsSource = lsts;
   }

這將為您提供以下螢幕作為輸出。您可以編輯 DataTemplate_Level2 以添加對象的更多特定數據。

替代文字

引用自:https://stackoverflow.com/questions/276808