1. Grid动态添加新的列和行。
首先添加一个Grid
<Grid x:Name="GTest" ShowGridLines="False" SizeChanged="GTest_SizeChanged" > </Grid>
this.GTest.RowDefinitions.Add(new RowDefinition() {Height=new GridLength(30) });
this.GTest.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
2. 为Grid动态添加Border的样式。
Border tempBorder = new Border();
tempBorder.BorderThickness = new Thickness(1);tempBorder.BorderBrush = new SolidColorBrush(Colors.Red);tempBorder.SetValue(Grid.ColumnProperty, 1);tempBorder.SetValue(Grid.ColumnSpanProperty, 2);this.GTest.Children.Add(tempBorder);3. 动态添加Button及Button的背景图片。
// Add new button
Button btnNew = new Button(); ImageBrush imageBrush = new ImageBrush(); imageBrush.ImageSource = new BitmapImage(new Uri(@"../Images/New.gif", UriKind.Relative)); btnNew.Background = imageBrush; btnNew.Width = 20; btnNew.Height = 20; btnNew.SetValue(Grid.ColumnProperty, 0); btnNew.SetValue(Grid.RowProperty, iContentStart); btnNew.Click += new RoutedEventHandler(btnNew_Click); titlePanel.Children.Add(btnNew);
4. 鼠标移动事件。
Rectangle rec = new Rectangle();
rec.Stroke = new SolidColorBrush(Colors.Black); rec.Fill = new SolidColorBrush(Colors.Orange); rec.MouseLeftButtonDown +=new MouseButtonEventHandler(rec_MouseLeftButtonDown); rec.MouseLeftButtonUp += new MouseButtonEventHandler(rec_MouseLeftButtonUp); rec.MouseMove += new MouseEventHandler(rec_MouseMove);
5, Grid的形状改变的时候,去改变Grid的类似那些Canvas控件的形状。
// First Remove the control in the Grid and ReBuild those controls that have been removed
private void GTest_SizeChanged(object sender, SizeChangedEventArgs e) { List<UIElement> controlsToRemove = new List<UIElement>();int RowsCount = this.GTest.RowDefinitions.Count;for (int i = 2; i < RowsCount; i++) { controlsToRemove = (from pControl in GTest.Children where (i == (int)pControl.GetValue(Grid.RowProperty)) select pControl).ToList<UIElement>();for (int j = 0; j < controlsToRemove.Count; j++) { GTest.Children.Remove(controlsToRemove[j]); }this.GTest.RowDefinitions.Remove(this.GTest.RowDefinitions[2]); } BuildTR(postCollection); }