在网格中拖动文本框

时间:2014-03-10 21:03:27

标签: c# wpf windows-phone-8

我想问一下如何移动一个网格的子文本框。此代码更改TextBox的左侧但不移动它。有没有办法将我的文本框的父级设置为画布。感谢您的回复。

private void Handle_Drag(object sender, ManipulationDeltaEventArgs e)
{
    TextBox Text = sender as TextBox;

    Text.Text = "I'm moved";
    double currentX = Canvas.GetLeft(Text);
    double currentY = Canvas.GetTop(Text);

    MessageBox.Show(currentX.ToString());
    MessageBox.Show(currentY.ToString()); 

    Canvas.SetLeft(Text, currentX + e.DeltaManipulation.Translation.X);
    Canvas.SetTop(Text, currentY + e.DeltaManipulation.Translation.Y); 
} 

2 个答案:

答案 0 :(得分:1)

尝试找到文本框的父级并从该网格中删除它。

   private void Handle_Drag(object sender,System.Windows.Input.ManipulationDeltaEventArgs e)
    {
        TextBox Text = sender as TextBox;

        var parent = Text.Parent as Grid;
        if (parent  != null)
        {
            parent.Children.Remove(Text);
            myCanvas.Children.Add(Text);
        }

        Text.Text = "I'm moved";
        double currentX = Canvas.GetLeft(Text);
        double currentY = Canvas.GetTop(Text);

        MessageBox.Show(currentX.ToString());
        MessageBox.Show(currentY.ToString());

        Canvas.SetLeft(Text, currentX + e.DeltaManipulation.Translation.X);
        Canvas.SetTop(Text, currentY + e.DeltaManipulation.Translation.Y); 
    }

或者您可以使用交互行为API进行拖动。 http://developer.nokia.com/community/wiki/Drag_%26_Drop_in_Windows_Phone

答案 1 :(得分:0)

首先,您必须将TextBox的父级设置为null

Text.Parent = null;

然后将TextBox添加为所需Canvas的子项

desiredCanvas.Children.Add(Text);

(假设Canvas的名称是Name =“desiredCanvas”)