Naming a variable/object with a string in WPF

Kathryn Porter 41 Reputation points
2021-09-29T12:30:03.33+00:00

Hello

I'm fairly new to programming and was just wondering if it was possible to use a string to dynamically name a new variable or object in WPF. I have seen on windows forms you could use me.controls to name things but this is not included on WPF and I haven't been able to find a definitive answer.

an example of this would be:

for i = 0 to 10
dim ("variable name " + i ) as new rectangle
next

The only reason I ask is I want to make a grid of rectangles that can be dynamically created when needed and that can be edited when needed too.

Thank you

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,854 questions
0 comments No comments
{count} votes

Accepted answer
  1. Hui Liu-MSFT 48,676 Reputation points Microsoft External Staff
    2021-09-30T05:28:34.453+00:00

    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:
    136573-3.gif


    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.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.