2009-04-14 130 views

回答

10

如果你知道的單元格和行,控制生活,你可以使用LINQ聲明來抓住它。

這裏有一個LINQ語句,將得到的第一個控制是第3列,第4行

var control = (from d in grid.Children 
       where Grid.GetColumn(d as FrameworkElement) == 3 
        && Grid.GetRow(d as FrameworkElement) == 4 
       select d).FirstOrDefault(); 
+0

不錯 - LINQ再一次消除了對循環的需求。 – 2009-04-15 06:28:15

1

您可以使用Grid.GetRow和Grid.GetColumn方法迭代網格的子節點檢查其行和列值,並在值匹配時替換目標內容。下面是WPF測試了樣品,但應在Silverlight中工作:

<Grid x:Name="SampleGrid"> 
    <Grid.RowDefinitions> 
     <RowDefinition /> 
     <RowDefinition /> 
     <RowDefinition /> 
     <RowDefinition /> 
    </Grid.RowDefinitions> 
    <Grid.ColumnDefinitions> 
     <ColumnDefinition /> 
     <ColumnDefinition /> 
     <ColumnDefinition /> 
    </Grid.ColumnDefinitions> 
    <Rectangle Fill="Red" Width="20" Height="20" Grid.Row="0" Grid.Column="0" /> 
    <Rectangle Fill="Orange" Width="20" Height="20" Grid.Row="0" Grid.Column="1" /> 
    <Rectangle Fill="Yellow" Width="20" Height="20" Grid.Row="0" Grid.Column="2" /> 
    <Rectangle Fill="Green" Width="20" Height="20" Grid.Row="1" Grid.Column="0" /> 
    <Rectangle Fill="Blue" Width="20" Height="20" Grid.Row="1" Grid.Column="1" /> 
    <Rectangle Fill="Indigo" Width="20" Height="20" Grid.Row="1" Grid.Column="2" /> 
    <Rectangle Fill="Violet" Width="20" Height="20" Grid.Row="2" Grid.Column="0" /> 
    <Rectangle Fill="Black" Width="20" Height="20" Grid.Row="2" Grid.Column="1" /> 
    <Rectangle Fill="Gray" Width="20" Height="20" Grid.Row="2" Grid.Column="2" /> 
    <Button Grid.Row="3" Grid.ColumnSpan="3" Margin="10" x:Name="Swap" Click="Swap_Click" Content="Swap"/> 
</Grid> 

在事件處理程序:

private void Swap_Click(object sender, RoutedEventArgs e) 
    { 
     Ellipse newEllipse = new Ellipse() { Fill = new SolidColorBrush(Colors.PaleGoldenrod), Width = 20d, Height = 20d }; 
     for (int childIndex = 0; childIndex < this.SampleGrid.Children.Count; childIndex++) 
     { 
      UIElement child = this.SampleGrid.Children[childIndex]; 
      if (Grid.GetColumn(child) == 2 && Grid.GetRow(child) == 2) 
      { 
       this.SampleGrid.Children.Remove(child); 
       Grid.SetRow(newEllipse, 2); 
       Grid.SetColumn(newEllipse, 2); 
       this.SampleGrid.Children.Add(newEllipse); 
      } 
     } 

    } 
+0

應該補充,如果你有大量的或行/ COLS你可能要添加一個break語句,以避免迭代剩下的孩子一旦你擊中了你的目標。 – 2009-04-14 15:12:46

0

你還記得去控制,我把在網格中添加一個私有變量:

private Control controlCentral = null; 

接下來,爲此變量添加添加到網格的控件,以便您可以使用刪除刪除網格的控件。

下面的代碼替換行0柱1的控制:

private void MostrarControlCentral(Control control) 
    { 
     if (control != null) 
     { 
      control.SetValue(Grid.RowProperty, 0); 
      control.SetValue(Grid.ColumnProperty, 1); 
     } 

     this.LayoutRoot.Children.Remove(this.controlCentral); 
     if (control != null) 
     { 
      this.LayoutRoot.Children.Add(control); 
     } 
     this.controlCentral=control; 
    } 
相關問題