WPF - 将数据从第A页传递到第B页

时间:2018-04-03 17:23:50

标签: wpf

所以我想在点击Canvas时传递数据。所以我有这个代码;

Canvas event_canvas = new Canvas();
                        event_canvas.Background = new SolidColorBrush(Color.FromRgb(66, 70, 77));
                        event_canvas.Width = 250;
                        event_canvas.Height = 60;
                        event_canvas.Margin = new Thickness(40, 0, 0, 0);
                        event_canvas.HorizontalAlignment = HorizontalAlignment.Left;
                        event_canvas.VerticalAlignment = VerticalAlignment.Top;
                        event_canvas.Cursor = Cursors.Hand;
                        #endregion

                        #region Grid (event_grid)
                        Grid event_grid = new Grid();
                        event_grid.Width = 250;
                        event_grid.Height = 60;
                        #endregion

                        #region TextBlock (event_text)
                        TextBlock event_text = new TextBlock();
                        event_text.VerticalAlignment = VerticalAlignment.Center;
                        event_text.HorizontalAlignment = HorizontalAlignment.Center;
                        event_text.Foreground = new SolidColorBrush(Color.FromRgb(255, 255, 255));
                        event_text.Text = e.name;
                        #endregion

                        event_grid.Children.Add(event_text); // Add the textblock to the grid
                        event_canvas.Children.Add(event_grid);  // Add the grid to the canvas                    
                        grid_events.Children.Add(event_canvas);    // Add the canvas to the main grid.

                        // Click event registration
                        event_canvas.MouseLeftButtonDown += Event_canvas_MouseLeftButtonDown;

然后在触发器中;

private void Event_canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
            {
                Page pg = new EventDetailPage();
                // Replaces all the content!!!!!
                this.Content = pg;
                //throw new NotImplementedException();
            }

我尝试添加此内容;

var param = ((TextBlock)sender).Text;
Page pg = new EventDetailPage(param);

但是这段代码不起作用,它会抛出一个我无法获得价值的错误。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

sender参数投放到Canvas,然后通过Grid'访问CanvasChildren收集,TextBlock通过Grid Children收集:

private void Event_canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Canvas canvas = (Canvas)sender;
    Grid event_grid = canvas.Children[0] as Grid;
    TextBlock event_text = event_grid.Children[0] as TextBlock;
    string text = event_text.Text;
    ...
}