0

this is function to make line with 4 points that give it place and name

int counter=0; 
public void CreateALine(double po1, double po2, double po3, double po4)
    {
        // Create a Line
        Line redLine = new Line();
        redLine.X1 = po1;
        redLine.Y1 = po2;
        redLine.X2 = po3;
        redLine.Y2 = po4;

        // Create a red Brush
        SolidColorBrush redBrush = new SolidColorBrush();
        redBrush.Color = Colors.Red;

        // Set Line's width and color
        redLine.StrokeThickness = 3;
        redLine.Stroke = redBrush;

        // Add line to the Grid.
        LayoutRoot.Children.Add(redLine);
        LayoutRoot.RegisterName("readline"+counter, redLine);
        counter++;            
    }

I want to create more than one line, Could i access to any line by its name? to make an event or control its Visibility like this :

      redline0.Visibility = Visibility.Collapsed;
      redline1.Visibility = Visibility.Visible;
  • Why don't you just keep their references in a member variable, e.g. in a `List` instead of accessing them by name? As a note, assigning the Stroke could simply be written as `redLine.Stroke = Brushes.Red;` – Clemens Aug 19 '17 at 20:16
  • You find the object by name the same way you would if you'd set the name in XAML. But really, your whole approach is wrong. You should not be creating UI objects in code-behind in the first place. You should have a view model object that represents a line, a collection of those objects that represents your program state, and then bind those objects in XAML with templates that make an actual line. Then modifying state on the objects is done however you like, and you can look those objects up however you like (for example, using an index into the collection). – Peter Duniho Aug 19 '17 at 20:22
  • I think in that but when i think if i give the line name ,i may be can control it by its name . so i search but i did not find anything , thank you.Clemens – Mohamed Abo AL Kear Aug 19 '17 at 20:22
  • If you use proper MVVM practices, you won't have to give the element a name. Your code-behind won't even need to _know_ about the element. It will be dealing strictly with the view model abstraction. – Peter Duniho Aug 19 '17 at 20:26

1 Answers1

0

var line = (Line)LayoutRoot.FindName(line_name);

José Pedro
  • 1,097
  • 3
  • 14
  • 24