You could use strings to dynamically name new variables or objects in WPF. For dynamically creating and editing Grid, you can refer to the following example
The code of xaml:
<StackPanel>
<ScrollViewer Height="300">
<ItemsControl Name="itemsControl" Background="Pink" ItemsSource="{Binding GridCollection}">
</ItemsControl>
</ScrollViewer>
<TextBox Name="tb" Text="{Binding Path=Num}" Width="200" Background="LightGreen" HorizontalAlignment="Right"/>
<Button Click="Button_Click" Width="200" HorizontalAlignment="Right" >create</Button>
</StackPanel>
The code of xaml.cs:
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace GridOfRectangles
{
public partial class MainWindow : Window,INotifyPropertyChanged
{
public MainWindow()
{
InitializeComponent();
tb.DataContext = this;
}
private string num;
public string Num
{
get { return num; }
set
{
if (value != num)
{
num = value;
OnPropertyChanged("Num");
}
}
}
private ObservableCollection<Grid> GridCollection { get; set; }
private void CreateGridDynamic ()
{
GridCollection = new ObservableCollection<Grid>();
for (int i = 0; i < 10; i++)
{
Grid dynamicGrid = new Grid();
var myBinding = new Binding("")
{
Source = int.Parse(Num)
};
dynamicGrid.SetBinding(Grid.WidthProperty, myBinding);
dynamicGrid.Height = 100;
dynamicGrid.Background = new SolidColorBrush(Colors.AliceBlue);
ColumnDefinition co1 = new ColumnDefinition();
ColumnDefinition co2 = new ColumnDefinition();
dynamicGrid.ColumnDefinitions.Add(co1);
dynamicGrid.ColumnDefinitions.Add(co2);
RowDefinition gridRow1 = new RowDefinition();
gridRow1.Height = new GridLength(45);
RowDefinition gridRow2 = new RowDefinition();
gridRow2.Height = new GridLength(45);
dynamicGrid.RowDefinitions.Add(gridRow1);
dynamicGrid.RowDefinitions.Add(gridRow2);
TextBox textBox = new TextBox();
textBox.Text = i.ToString();
textBox.FontWeight = FontWeights.Bold;
textBox.Foreground = new SolidColorBrush(Colors.Green);
Grid.SetRow(textBox, 0);
Grid.SetColumn(textBox, 0);
dynamicGrid.Children.Add(textBox);
GridCollection.Add(dynamicGrid);
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
CreateGridDynamic();
itemsControl.ItemsSource = GridCollection;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
The picture of result:
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.