从发件人处获取子控件内容

时间:2014-12-17 11:26:05

标签: c# wpf canvas children

如何从发件人的孩子那里获得价值?

MouseUp上的

Canvas会创建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);
    }

当用户点击已存在的Grid时,我希望显示包含MessageBox的{​​{1}},在这种情况下,“06:00”

这不起作用(我也尝试了其他一些,结果相同)

timeLabel.Content

错误

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

3 个答案:

答案 0 :(得分:2)

您可以使用Registername作为标签控件并提供名称,然后使用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());
            }
    }

答案 1 :(得分:1)

您为网格命名,但您尝试按名称查找标签。选择一个或另一个。也许,命名您的标签而不是网格是最有意义的。

答案 2 :(得分:0)

您应该为您的标签命名,然后找到名称

您可以使用第一个网格子项:

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