简体   繁体   English

在wp7中动态添加控件和手势侦听器

[英]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. 与StackPanel不同,Canvas控件的行为类似于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. 对于Canvas中的每个元素,您需要指定Canvas.Top和Canvas.Left属性。 Omitting these values will result in your elements being positioned in the top left corner of the Canvas, at position 0,0. 忽略这些值将导致您的元素位于“画布”的左上角,位置0,0。

So you need to provide Left and Top properties as shown below, 因此,您需要提供Left和Top属性,如下所示,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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