I have a grid and I need to dynamically replace a control that resides in one of the cells. I don't know in terms of syntax to pinpoint the grid cell, as where do I put in the row and column number so I can delete whatever is in it.
If you know the cell and row that the control lives in, you can use a LINQ statement to grab it.
Here's a LINQ statement that will get the first control that is in column 3, row 4.
var control = (from d in grid.Children
where Grid.GetColumn(d as FrameworkElement) == 3
&& Grid.GetRow(d as FrameworkElement) == 4
select d).FirstOrDefault();
You could iterate the children of the grid checking their row and column values using the Grid.GetRow and Grid.GetColumn methods and replace the targeted content when the values match. Here's a sample tested in WPF, but should work in 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>
In the event handler:
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With