简体   繁体   中英

Get child control content from sender

How do I get a value from the sender's children?

MouseUp on a Canvas creates a Grid .

    private void ScrollViewer_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Grid grid = new Grid();

        Label timeLabel = new Label();
            timeLabel.Content = "06:00"; //this could be anything
            timeLabel.Name = "TimeStart"

          grid.Children.Add(timeLabel);
            canvas.Children.Add(grid);
                grid.MouseDown += new MouseButtonEventHandler(ClickEvent);
    }

When the user clicks on an already existing Grid , I want a MessageBox containing timeLabel.Content to appear, in this case, "06:00"

This is not working (I've tried some others as well, same result)

    void ClickEvent(object sender, RoutedEventArgs e)
    {
        Grid test = (Grid)sender;
        Label label = (Label)test.FindName("TimeStart");
        MessageBox.Show(label.Content.ToString());
    }

Error

    An unhandled exception of type 'System.NullReferenceException' occurred in MissionControl M.exe

        Additional information: Object reference not set to an instance of an object.

You Can use Registername for your label control and give a name, then access it using FindName

  private void ScrollViewer_MouseUp(object sender, MouseButtonEventArgs e)
        {
             NameScope.SetNameScope(grid, new NameScope());
             Label timeLabel = new Label();
             timeLabel.Name = "label1";
             grid.RegisterName("label1", timeLabel);
            timeLabel.Content = "06:00";                
        }
        void ClickEvent(object sender, RoutedEventArgs e)
        {
            Grid test = (Grid)sender;
            if (test != null)
            {
                Label label = (Label)test.FindName("label1");
                MessageBox.Show(label.Content.ToString());
            }
    }

You named your grid, yet you try to find your label by name. Pick one or the other. Probably, naming your label instead of your grid makes the most sense.

you should name you lable and then FindName

or you can use then first grid children :

Grid test = (Grid)sender;
if(test != null)
{
      Label label = test.Children[0] as Lable;
      MessageBox.Show(label.Content.ToString());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM