简体   繁体   中英

Dynamically adding controls and gesture listener in wp7

I want to add some images or controls dynamically in my canvas control and for each control I want to get its gesture event. How I Would I get that what will be the best approach.

void AddText()
        {
            TextBlock name = new TextBlock();
            name.Text = "This is text " + Count;
            Random rnd1 = new Random();
            name.Width = rnd1.Next(0, 400);
            name.Height = rnd1.Next(0, 800);
            var gl = GestureService.GetGestureListener(name);
            gl.Tap += new EventHandler<GestureEventArgs>(GestureListener_Tap);
            gl.Hold += new EventHandler<GestureEventArgs>(GestureListener_Hold);
            canvas1.Children.Add(name);
        }


private void GestureListener_Tap(object sender, GestureEventArgs e)
{
    MessageBox.Show("I Am Tapped");
}

private void GestureListener_Hold(object sender, GestureEventArgs e)
{
    MessageBox.Show("I Am Holded");
}

But in this way my all controls are placed on same place even I used random function for thier width and height. And other thing when I tap on any textblock that i created with this way. It calls all gesture events.

Unlike StackPanel, Canvas control behaves like absolute positioning in HTML/CSS. Each element will be given its own specific location on the page. With elements absolutely positioned, they don't adjust. Elements will overlap, without having any positioning-related effect on its neighbors.

<Canvas>
  <Rectangle Fill="Red" Width="100" Height="100" Canvas.Top="100" Canvas.Left="100" />
  <Rectangle Fill="Orange" Width="100" Height="100" Canvas.Top="100" Canvas.Left="200" />
  <Rectangle Fill="Green" Width="100" Height="100" Canvas.Top="200" Canvas.Left="100" />
  <Rectangle Fill="Blue" Width="100" Height="100" Canvas.Top="200" Canvas.Left="200" />
</Canvas>

For each element in your Canvas, you will need to specify the Canvas.Top and Canvas.Left properties. Omitting these values will result in your elements being positioned in the top left corner of the Canvas, at position 0,0.

So you need to provide Left and Top properties as shown below,

Canvas.SetLeft(name, 50);
Canvas.SetTop(name, 100);

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